Python: Count repeated characters in a string
Python String: Exercise-42 with Solution
Count repeated characters in string.
Write a python program to 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:
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.
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://w3resource.com/python-exercises/string/python-data-type-string-exercise-42.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics