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
String: programming 'r' appears 2 times 'g' appears 2 times 'm' appears 2 times
How it works
- The first loop counts every character, using the character as the key and its count as the value.
- The second loop goes through the dictionary and prints only the characters with a count above 1.
foundremembers whether any duplicate was printed, so a string like "python" gets a clear message instead of no output.- Spaces count as characters too, so skip them with
if ch == " ": continuewhen checking sentences.
Other ways to write it
Using collections.Counter
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
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.
Related programs
- Remove Duplicate Characters from a String
- Find the First Non-Repeating Character
- Count the Frequency of Each Character in a String
- Find Duplicates in a List
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Words in a String
- Remove Punctuation from a String
All Python programs · CBSE class 12 practical file · Python exercises