协慌网

登录 贡献 社区

计算字符串中字符的出现次数

计算字符串中字符出现次数的最简单方法是什么?

例如,计算'Mary had a little lamb'出现'a'的次数

答案

str.count(sub [,start [,end]])

返回[start, end]范围内 substring sub的非重叠出现次数。可选参数startend被解释为切片表示法。

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

你可以使用count()

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

正如其他答案所说,使用字符串方法 count()可能是最简单的,但如果你经常这样做,请查看collections.Counter

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