Counting repeated characters in a string in Python

Viewed 328799

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?

18 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])

My first idea was to do this:

chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "i am checking this string to see how many times each character appears"

for char in chars:
  count = check_string.count(char)
  if count > 1:
    print char, count

This is not a good idea, however! This is going to scan the string 26 times, so you're going to potentially do 26 times more work than some of the other answers. You really should do this:

count = {}
for s in check_string:
  if s in count:
    count[s] += 1
  else:
    count[s] = 1

for key in count:
  if count[key] > 1:
    print key, count[key]

This ensures that you only go through the string once, instead of 26 times.

Also, Alex's answer is a great one - I was not familiar with the collections module. I'll be using that in the future. His answer is more concise than mine is and technically superior. I recommend using his code over mine.

Python 2.7+ includes the collections.Counter class:

import collections
results = collections.Counter(the_string)
print(results)

This is the shortest, most practical I can comeup with without importing extra modules.

text = "hello cruel world. This is a sample text"
d = dict.fromkeys(text, 0)
for c in text: d[c] += 1

print d['a'] would output 2

And it's also fast.

You want to use a dict.

#!/usr/bin/env python

input = "this is a string"

d = {}

for c in input:
    try:
        d[c] += 1
    except:
        d[c] = 1

for k in d.keys():
    print "%s: %d" % (k, d[k])

You can use a dictionary:

s = "asldaksldkalskdla"
dict = {}
for letter in s:
 if letter not in dict.keys():
  dict[letter] = 1
 else:
  dict[letter] += 1

print dict

I can count the number of days I know Python on my two hands so forgive me if I answer something silly :)

Instead of using a dict, I thought why not use a list? I'm not sure how lists and dictionaries are implemented in Python so this would have to be measured to know what's faster.

If this was C++ I would just use a normal c-array/vector for constant time access (that would definitely be faster) but I don't know what the corresponding datatype is in Python (if there's one...):

count = [0 for i in range(26)]

for c in ''.join(s.lower().split()): # get rid of whitespaces and capital letters
    count[ord(c) - 97] += 1          # ord('a') == 97

It's also possible to make the list's size ord('z') and then get rid of the 97 subtraction everywhere, but if you optimize, why not all the way :)

EDIT: A commenter suggested that the join/split is not worth the possible gain of using a list, so I thought why not get rid of it:

count = [0 for i in range(26)]

for c in s:
    if c.isalpha(): count[ord(c.lower()) - 97] += 1
inputString =  input("Enter a String:")
countedArray = {}

for char in inputString:
    if char in countedArray:  
        countedArray[char] += 1    
    else:
        countedArray[char] = 1
    
print(countedArray) 

''' #TO find the repeated char in string can check with below simple python program.

   str1 = "aaaaabbaabbcc"
    k = list(str1)
    dict1 = {}
    for char in k:
        cnt = 0
        for i in range(len(k)):
            if char == k[i]:
               cnt=cnt+1
        dict1[char] = cnt 

output you will get is  :  {'a': 7, 'b': 4, 'c': 2}
print (dict1) '''
   
s = 'today is sunday i would like to relax'
numberOfDuplicatedChar = len(s) - len(set(s))

#no duplicated element in set.

Related