+4 votes
in Programming Languages by (12.7k 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

+1 vote
by (27.2k points)

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})


...