![](/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.