Advertisement
Advertisement


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'

2018/02/13
1
968
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
2020/06/20
1356
6/20/2020 9:12:55 AM

You can use count() :

>>> 'Mary had a little lamb'.count('a')
4
2016/10/05

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']
2019/03/08

Regular expressions maybe?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
2009/07/20

myString.count('a');

more info here

2009/07/20

Python-3.x:

"aabc".count("a")

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.

2020/01/14

Source: https://stackoverflow.com/questions/1155617
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]