+4 votes
in Programming Languages by (40.5k points)
I want to count the occurrence of each character in a given word. Is there any Python function for this operation?

E.g.

In "ababcbacaba", a=5, b=3, and c=2

1 Answer

+2 votes
by (73.8k points)
selected by
 
Best answer

You can use the Counter() module of the collections class. A Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

Here is an example:

>>> from collections import Counter

>>> a="ababcbacaba"

>>> Counter(a)

Counter({'a': 5, 'b': 4, 'c': 2})


...