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?
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.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With