Count the number of occurrences of a character in a string
What's the simplest way to count the number of occurrences of a character in a string?
e.g. count the number of times that 'a'
appears in 'Mary had a little lamb'
.
Solution 1:
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring
sub
in the range[start, end]
. Optional argumentsstart
andend
are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
Solution 2:
You can use count() :
>>> 'Mary had a little lamb'.count('a')
4
Solution 3:
As other answers said, using the string method count() is probably the simplest, but if you're doing this frequently, check out collections.Counter:
from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print counter['a']