如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
不超过这个IMHO -你可以添加上或下的方法
def count_letter_in_str(string,letter):
return string.count(letter)
其他回答
python - 3. x:
"aabc".count("a")
Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。
不使用Counter(), count和regex获得所有字符计数的另一种方法
counts_dict = {}
for c in list(sentence):
if c not in counts_dict:
counts_dict[c] = 0
counts_dict[c] += 1
for key, value in counts_dict.items():
print(key, value)
正则表达式?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
要获得所有字母的计数,请使用集合。计数器:
>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4
这个简单直接的函数可能会有帮助:
def check_freq(x):
freq = {}
for c in set(x):
freq[c] = x.count(c)
return freq
check_freq("abbabcbdbabdbdbabababcbcbab")
{'a': 7, 'b': 14, 'c': 3, 'd': 3}
如果需要理解:
def check_freq(x):
return {c: x.count(c) for c in set(x)}