Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Counting characters in string (See related posts)

>>> s = 'a;jfkd;aflhakfhaskfjalghlakfhfnkjafyksd'
>>> cnt = {}
>>> for c in s:
	cnt[c] = cnt.get(c,0) + 1

>>> print cnt
{'a': 7, 'd': 2, 'g': 1, 'f': 7, 'h': 4, 'k': 6, 'j': 3, 'l': 3, 'n': 1, 's': 2, 'y': 1, ';': 2}

This can be used to count any distribution.
Note the use of dict.get(key,default) to set to 0
if the key is not avaiable.
If this were perl, I would just do a
cnt[c] += 1

But python will give an error instead of returning 0.
It's not too bad, though.

Comments on this post

foudhos posts on Sep 06, 2005 at 17:47
>>> s = 'a;jfkd;aflhakfhaskfjalghlakfhfnkjafyksd'
>>> dict((c, s.count(c)) for c in s)
{'a': 7, 'd': 2, 'g': 1, 'f': 7, 'h': 4, 'k': 6, 'j': 3, 'l': 3, 'n': 1, 's': 2, 'y': 1, ';': 2}

You need to create an account or log in to post comments to this site.


Click here to browse all 4834 code snippets

Related Posts