Coder Perfect

Count the number of times a character appears in a string.

Problem

What’s the simplest way to count how many times a character appears in a string?

Count how many times the letter ‘a’ appears in ‘Mary had a small lamb.’

Asked by Mat

Solution #1

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

Answered by Ogre Codes

Solution #2

You may use count() to get the following results:

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

Answered by eduffy

Solution #3

Using the string function count() is generally the simplest, but if you’re doing this regularly, collections would be a better option. Counter:

from collections import Counter
my_str = "Mary had a little lamb"
counter = Counter(my_str)
print counter['a']

Answered by Brenden Brown

Solution #4

Regular expressions maybe?

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

Answered by Sinan Taifour

Solution #5

Python-3.x:

"aabc".count("a")

Answered by Aaron Fi

Post is based on https://stackoverflow.com/questions/1155617/count-the-number-of-occurrences-of-a-character-in-a-string