Counting hashable objects

How can we count the number of occurance of alphabets in a string? As soon as this question hits, many of us starts to think about loops… But there is a better solution in python called ‘collections.Counter’

#! /usr/bin/python

import collections
the_string = 'sfsdfsdfsdfdsfsdfsdfsdfsdf'
results = collections.Counter(the_string)

# output
# Counter({'s': 9, 'f': 9, 'd': 8})

Check the official python documentation for more details.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s