w3resource

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 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

Python Code Editor:

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 Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/string/python-data-type-string-exercise-42.php