str.count(sub [,start [,end]])
返回
[start, end]
范围内 substringsub
的非重叠出现次数。可选参数start
和end
被解释为切片表示法。
>>> 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']