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
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.
Enter a word: programming progamin
How it works
seenstarts empty. Each new character is added to it and toresult.- When a character comes again,
ch not in seenisFalse, so it is skipped. The first "r", "g" and "m" stay, and the later copies are removed. - Checking
inon a set is fast, even when the set is large. On a list or a string, Python has to look at every item.
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:
text = "programming" print("".join(dict.fromkeys(text)))
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:
print(sorted(set("programming")))
['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.