Count the number of occurences of characters in a string in Python

To count the number of occurrences of a character in a string, use the string’s count() method:

string = 'The quick brown fox jumps over the lazy dog'
print(string.count('z'))
1

Note that you can also count substrings with count():

string = 'spam, eggs, ham, spam, spam, spam'
print(string.count('spam'))
4

To count the number of occurrences of all characters in a string, use a collections.Counter:

string = 'The quick brown fox jumps over the lazy dog'
counter = Counter(string)
print(counter)
Counter({'a': 5, ' ': 5, 'm': 5, ',': 5, 's': 5, 'p': 4, 'g': 2, 'e': 1, 'h': 1})