Count the number occurrences of a character in a string

What's the simplest way to count the number of occurrences of a character in a string?

eg count the number of times 'a' appears in 'Mary had a little lamb'


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

Return the number of non-overlapping occurrences of substring sub in the range [start, end] . Optional arguments start and end are interpreted as in slice notation.

>>> 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/75408.html

上一篇: UIRefreshControl在景观

下一篇: 计算字符串中字符的出现次数