计算字符串中字符的出现次数
计算字符串中字符出现次数的最简单方法是什么?
例如,计算'Mary had a little lamb'
出现'a'
的次数
str.count(sub [,start [,end]])
返回[start, end]
范围内子串sub
的非重叠次数。 可选参数start
和end
被解释为切片符号。
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
你可以使用count():
>>> 'Mary had a little lamb'.count('a')
4
正如其他答案所说,使用字符串方法count()可能是最简单的,但如果您经常这样做,请检查集合.Counter:
from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
print counter['a']
链接地址: http://www.djcxy.com/p/75407.html
上一篇: Count the number occurrences of a character in a string