DZone 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
>>> 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
Snippets Manager replied on Wed, 2009/07/15 - 3:38pm
Snippets Manager replied on Mon, 2009/01/12 - 12:16am
Snippets Manager replied on Mon, 2012/05/07 - 2:13pm
>>> 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}