Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting repeated characters in a string in Python

Tags:

python

I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter?

Update (in reference to Anthony's answer): Whatever you have suggested till now I have to write 26 times. Is there an easier way?

like image 577
Hick Avatar asked Jun 13 '09 19:06

Hick


People also ask

How do you count occurrences of a string in Python?

count() One of the built-in ways in which you can use Python to count the number of occurrences in a string is using the built-in string . count() method. The method takes one argument, either a character or a substring, and returns the number of times that character exists in the string associated with the method.

How do you find all occurrences of a character in a string Python?

Use the string. count() Function to Find All Occurrences of a Substring in a String in Python. The string. count() is an in-built function in Python that returns the quantity or number of occurrences of a substring in a given particular string.


1 Answers

import collections  d = collections.defaultdict(int) for c in thestring:     d[c] += 1 

A collections.defaultdict is like a dict (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callable. Most popular are defaultdict(int), for counting (or, equivalently, to make a multiset AKA bag data structure), and defaultdict(list), which does away forever with the need to use .setdefault(akey, []).append(avalue) and similar awkward idioms.

So once you've done this d is a dict-like container mapping every character to the number of times it appears, and you can emit it any way you like, of course. For example, most-popular character first:

for c in sorted(d, key=d.get, reverse=True):   print '%s %6d' % (c, d[c]) 
like image 199
Alex Martelli Avatar answered Sep 21 '22 13:09

Alex Martelli