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

About this user

Korakot Chaovavanich http://korakot.stumbleupon.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Counting characters in string

   1  
   2  >>> s = 'a;jfkd;aflhakfhaskfjalghlakfhfnkjafyksd'
   3  >>> cnt = {}
   4  >>> for c in s:
   5  	cnt[c] = cnt.get(c,0) + 1
   6  
   7  >>> print cnt
   8  {'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
   1  cnt[c] += 1

But python will give an error instead of returning 0.
It's not too bad, though.
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS