Count the number occurrences of a character in a string


Question

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

e.g. count the number of times 'a' appears in 'Mary had a little lamb'

1
889
2/13/2018 5:44:19 AM

Accepted Answer

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
1242
12/1/2016 7:16:28 AM

You can use count() :

>>> 'Mary had a little lamb'.count('a')
4

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon