PythonMastery
Python programs · Strings · beginner

Remove duplicate characters from a string in Python

Keep only the first copy of each character and keep the original order. Shown with a loop and a set, then with dict.fromkeys().

Go through the string and keep each character only the first time you see it. A set remembers which characters you have already seen.

The program

python
text = input("Enter a word: ")

seen = set()
result = ""
for ch in text:
    if ch not in seen:
        seen.add(ch)
        result += ch

print(result)

Typed in this example: programming. Press Run to type your own.

output
Enter a word: programming
progamin

How it works

Another way: dict.fromkeys()

A dictionary cannot have the same key twice, and it keeps keys in the order they were added. dict.fromkeys(text) makes one key per character, and "".join() puts the keys back together:

python
text = "programming"
print("".join(dict.fromkeys(text)))
output
progamin

Why not just use set()?

A set removes duplicates too, but it does not keep the order. The letters can come back in any order, so the result is not a useful word:

python
print(sorted(set("programming")))
output
['a', 'g', 'i', 'm', 'n', 'o', 'p', 'r']

sorted() is used here only so the output is the same each time. Without it, the order of a set of strings can change from one run to the next.

Learn the idea: Working with Strings, Sets: Unordered, Unique, Lightning Fast, Dictionaries