Python: Count repeated characters in a string

Python String: Exercise-42 with Solution

Write a python program to count repeated characters in a string.

Python String Exercises: Count repeated characters in a string

Sample Solution:-

Python Code:

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

for c in sorted(d, key=d.get, reverse=True):
  if d[c] > 1:
      print('%s %d' % (c, d[c]))

Sample Output:

o 4                                                                                                           
e 3                                                                                                           
h 2                                                                                                           
t 2                                                                                                           
r 2                                                                                                           
u 2                             


Flowchart: Count repeated characters in a string

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to strip a set of characters from a string.
Next: Write a Python program to print the square and cube symbol in the area of a rectangle and volume of a cylinder.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz

Python: Tips of the Day

Set comprehension:

>>> m = {x ** 2 for x in range(5)}
>>> m
{0, 1, 4, 9, 16}