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

如。“a”在“Mary had a little lamb”中出现了4次。


当前回答

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

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

其他回答

我不知道“最简单的”,但简单的理解可以做到:

>>> my_string = "Mary had a little lamb"
>>> sum(char == 'a' for char in my_string)
4

利用内置的和,生成器理解和bool是整数的子类的事实:如何乘字符等于'a'。

你可以使用循环和字典。

def count_letter(text):
    result = {}
    for letter in text:
        if letter not in result:
            result[letter] = 0
        result[letter] += 1
    return result
myString.count('a');

更多信息请点击这里

不使用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)

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

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