Count the number occurrences of a character in a string
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'
Return the number of non-overlapping occurrences of substring
subin the range
[start, end]. Optional arguments
endare interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb' >>> sentence.count('a') 4
Read more... Read less...
Regular expressions maybe?
import re my_string = "Mary had a little lamb" len(re.findall("a", my_string))