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

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

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


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

返回[start, end]范围内子串sub的非重叠次数。 可选参数startend被解释为切片符号。

>>> 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

下一篇: data post image and json same time