如何计算字符串中字符出现的次数?

如。“a”在“Mary had a little lamb”中出现了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}

其他回答

这是公认答案的延伸,你应该在文本中寻找所有字符的计数。

# 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}

要获得所有字母的计数,请使用集合。计数器:

>>> from collections import Counter
>>> counter = Counter("Mary had a little lamb")
>>> counter['a']
4

不超过这个IMHO -你可以添加上或下的方法

def count_letter_in_str(string,letter):
    return string.count(letter)
myString.count('a');

更多信息请点击这里

Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4