Take the 2-minute tour ×

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'

share|improve this question

7 Answers 7

>>> 'Mary had a little lamb'.count ('a')
share|improve this answer

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
str = "Mary had a little lamb"
counter = Counter(str)
print counter['a']
share|improve this answer

Regular expressions maybe?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
share|improve this answer
A fine idea, but overkill in this case. The string method 'count' does the same thing with the added bonus of being immediately obvious about what it is doing. –  nilamo Jul 20 '09 at 20:18
why negative rate, maybe someone needs this kind of code for something similar. my vote up –  kiltek Mar 31 '12 at 10:18
agree with kiltek -- this is just the more general case... –  C. Reed Apr 1 '12 at 14:28
Definite overkill but i agree with kiltek –  darkyen00 Sep 5 '13 at 15:13
This should be downvoted because it is the least efficient way possible to count characters in a string. If the goal is simply to count characters, as the question indicates, it would be hard to find a worse way to do the job. In terms of memory and processor overhead, this solution is definitely to be avoided. No one will ever "need" to use this method to find the count of characters in a string. –  Christopher Oct 21 '13 at 18:04

more info here

share|improve this answer
share|improve this answer

Regular expressions are very useful if you want case-insensitivity (and of course all the power of regex).

my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m")   # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))

Be aware that the regex version takes on the order of ten times as long to run, which will likely be an issue only if my_string is tremendously long, or the code is inside a deep loop.

share|improve this answer

Your Answer


