![](/img/trans.png)
[英]How to search string using regular expression for string contains characters alphabets and special characters like -, () using python
[英]How to count special characters, Alphabets and numbers from a string in python?
string = '98 people are present @ seminar'
def count(string):
d={}
for t in string:
d[t] = string.count(t)
for k in sorted(d):
print(k+':' + str(d[k]))
count(string)
在這里我想為特殊字符和數字添加計數器。 還想獲取字符串的用戶輸入。 我怎么做?
要求用戶輸入字符串使用
variableName = input(PROMPT)
要進行計數,請列出 nums、字母列表和 rest 將是特殊字符 然后循環遍歷列表並使用 if 語句檢查字母是否在帶有.contains()
的字符串中
代碼看起來像這樣:
letters = "abcdefghijklmnopqrstuvwxyz"
numbers = "0123456789"
def countString(inputString,characterType):#inputString is the string you want to check characterType is what you want to check for
count = 0
inputString = inputString.lower()
if characterType == "numbers":
for i in inputString:
if not(numbers.count(i) == 0):
count += 1
elif characterType == "letters":
for i in inputString:
if not(letters.count(i) == 0):
count += 1
elif characterType == "specialChars":
for i in inputString:
if numbers.count(i) == 0 and letters.count(i) == 0 and not(i == " ") :
count += 1
return count
Python 有多種字符串方法來幫助區分字母和數字字符串。 您可以測試這些並根據該測試進行計數。
def count(string):
d={'letters': 0, 'numbers': 0, 'other': 0}
for t in string:
if t.isalpha():
d['letters'] += 1
elif t.isdigit():
d['numbers'] += 1
else:
d['other'] += 1 # this will include spaces
return d
string = input('enter some text: ')
# 98 people are present @ seminar
counts = count(string)
print(counts)
# {'letters': 23, 'numbers': 2, 'other': 6}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.