w3resource

Python: Count repeated characters in a string


Count repeated characters in string.

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 the 'collections' module to use the 'defaultdict' class.
import collections

# Define a string 'str1' with a sentence.
str1 = 'thequickbrownfoxjumpsoverthelazydog'

# Create a defaultdict 'd' with integer values as the default type.
d = collections.defaultdict(int)

# Iterate through each character in the string 'str1'.
# Update the counts of each character in the 'd' dictionary.
for c in str1:
    d[c] += 1

# Iterate through the characters in 'd' in descending order of their counts.
for c in sorted(d, key=d.get, reverse=True):
    # Check if the character occurs more than once.
    if d[c] > 1:
        # Print the character and its count.
        print('%s %d' % (c, d[c])) 

Sample Output:

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

Flowchart:

Flowchart: Count repeated characters in a string

For more Practice: Solve these Related Problems:

  • Write a Python program to count and display each character in a string that occurs more than once using collections.Counter.
  • Write a Python program to iterate over a string and print only those characters that appear repeatedly along with their counts.
  • Write a Python program to use a dictionary to tally character occurrences and then output only the characters with counts greater than one.
  • Write a Python program to implement a function that returns a formatted string showing repeated characters and their frequencies.

Go to:


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.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.