如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
正则表达式?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
其他回答
myString.count('a');
更多信息请点击这里
你可以使用.count():
>>> 'Mary had a little lamb'.count('a')
4
这是公认答案的延伸,你应该在文本中寻找所有字符的计数。
# Objective: we will only count for non-empty characters
text = "count a character occurrence"
unique_letters = set(text)
result = dict((x, text.count(x)) for x in unique_letters if x.strip())
print(result)
# {'a': 3, 'c': 6, 'e': 3, 'u': 2, 'n': 2, 't': 2, 'r': 3, 'h': 1, 'o': 2}
不超过这个IMHO -你可以添加上或下的方法
def count_letter_in_str(string,letter):
return string.count(letter)
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
print(key, a.count(key))