Python Program to Remove Duplicate Characters from a String
Beginner · Strings
This program removes repeated characters from a string and keeps only the first time each one appears, so "programming" becomes "progamin". The characters that remain stay in their original order.
Program
Original: programming Without duplicates: progamin
How it works
resultstarts empty and collects the characters to keep.if ch not in resultchecks whether the character has been kept already, so only new characters are added.- Because the loop reads the string from left to right, the first copy of each character survives and later copies are dropped.
- The check is case-sensitive, so "P" and "p" count as different characters.
Other ways to write it
Using dict.fromkeys()
programming -> progamin
dict.fromkeys(text) makes a dictionary with each character as a key. Keys cannot repeat and keep the order they were added in, so joining them gives the answer in one line.
Using a set (the order is lost)
Unique characters, sorted: agimnopr Number of different characters: 8
A set keeps one copy of each character but has no order, and the order of a set of strings can even change from one run to the next, so the result is sorted before printing.
Try it yourself
Change the check to ignore case, so that "Mississippi River" keeps only one i, one s and one r.
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
- Find Duplicate Characters in a String
- Remove Duplicates from a List
- Find the First Non-Repeating Character
- Count Vowels, Consonants, Uppercase and Lowercase Letters
- Check a Palindrome String
- Reverse a String
- Generate a Random Password
- Count the Frequency of Each Character in a String
- Count the Words in a String
All Python programs · CBSE class 12 practical file · Python exercises