views:

1264

answers:

5

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'

A: 

Regular expressions maybe?

import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
Sinan Taifour
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
+15  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.

>>> a='Mary had a little lamb'
>>> a.count('a')
4
Dennis Baker
+2  A: 
>>> 'Mary had a little lamb'.count ('a')
4
eduffy
+3  A: 
myString.count('a');

more info here

Finer Recliner
+1  A: 
"aabc".count("a")
Aaron F.