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

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


当前回答

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

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

其他回答

正则表达式?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))

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

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

使用数:

sentence = 'A man walked up to a door'
print(sentence.count('a'))
# 4

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

def count_letter_in_str(string,letter):
    return string.count(letter)

你可以使用.count():

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