Editor

Python Program to Find Duplicate Characters in a String

Beginner · Strings

A duplicate character is one that appears more than once in a string; in "programming" the letters r, g and m each appear twice. This program counts every character with a dictionary and then prints the ones whose count is greater than 1.

Program

duplicate_characters.py
text = "programming" # or: text = input("Enter a string: ")
counts = {}
for ch in text:
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
print("String:", text)
found = False
for ch, count in counts.items():
if count > 1:
print(f"'{ch}' appears {count} times")
found = True
if not found:
print("There are no duplicate characters")
Output
String: programming
'r' appears 2 times
'g' appears 2 times
'm' appears 2 times

How it works

  1. The first loop counts every character, using the character as the key and its count as the value.
  2. The second loop goes through the dictionary and prints only the characters with a count above 1.
  3. found remembers whether any duplicate was printed, so a string like "python" gets a clear message instead of no output.
  4. Spaces count as characters too, so skip them with if ch == " ": continue when checking sentences.

Other ways to write it

Using collections.Counter

Using collections.Counter
from collections import Counter
text = "mississippi"
counts = Counter(text)
duplicates = [ch for ch, n in counts.items() if n > 1]
print("String:", text)
print("Duplicate characters:", duplicates)
Output
String: mississippi
Duplicate characters: ['i', 's', 'p']

Counter does the counting, and the list comprehension keeps the characters that appear more than once, in the order they first appear.

Using count() without a dictionary

Using count() without a dictionary
text = "programming"
duplicates = []
for ch in text:
if text.count(ch) > 1 and ch not in duplicates:
duplicates.append(ch)
print("Duplicate characters:", duplicates)
Output
Duplicate characters: ['r', 'g', 'm']

This is easy to read, but count() scans the whole string again for every character, so it slows down on very long strings.

Try it yourself

Make the check ignore case, so that "P" and "p" in "Pepper" count as the same letter.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises