Skip to content

Write a Python program to find the repeated character in a given string

  • by

It’s easy in Python to find the repeated character in a given string. There are many ways to do it like using alphabets, for-loop, or collections.

Python program to find the repeated character in a given string Example

Simple example code.

Basic ways scan the string 26 times

chars = "abcdefghijklmnopqrstuvwxyz"
check_string = "Write a Python program to find the repeated character in a given string"
l_string = check_string.lower()

for char in chars:
    count = l_string.count(char)
    print(char, count, end=', ')

Output:

Python program to find the repeated character in a given string

Another way is only to go through the string once

Space will also count in this method so apply if condition to remove space in the count.


check_string = "Write a Python program to find the repeated character in a given string"
count = {}
for s in check_string:
    if s != ' ':
        if s in count:
            count[s] += 1
        else:
            count[s] = 1
print(count)

Using collections

Need to import collection module.

import collections

check_string = "Write a Python program to find the repeated character in a given string"
d = collections.defaultdict(int)
for c in check_string:
    d[c] += 1

print(d)

Do comment if you have any doubts and suggestions on this Python char program.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *