Remove All Duplicates from a Given String in Python (original) (raw)

Last Updated : 4 Nov, 2025

The task is to remove all duplicate characters from a string while keeping the first occurrence of each character in its original order. **For example:

**Input: "geeksforgeeks"
**Output: "geksfor"

Let’s explore multiple methods to remove duplicates from a string in Python.

Using dict.fromkeys()

This method converts the string into a dictionary where each character is a key. Since dictionary keys are unique and insertion order is preserved, it effectively removes duplicates while keeping the original order.

Python `

s = "geeksforgeeks" res = "".join(dict.fromkeys(s)) print(res)

`

**Explanation:

Using OrderedDict.fromkeys()

OrderedDict works similarly to a dictionary but is explicitly designed to preserve order. It ensures duplicates are removed while keeping the insertion sequence intact.

Python `

from collections import OrderedDict s = "geeksforgeeks" res = "".join(OrderedDict.fromkeys(s)) print(res)

`

**Explanation:

Using for Loop with a Set

This approach removes duplicates by iterating through the string with a for loop, tracking previously seen characters using a set. The first occurrence of each character is added to the result string, which preserves the order.

Python `

s = "geeksforgeeks" seen = set()
res = ""
for char in s: if char not in seen: seen.add(char) res += char

print(res)

`

**Explanation:

Using List Comprehension with Slicing

This method uses list comprehension and checks each character against the substring before it to remove duplicates. While functional, it is slower for large strings due to repeated slicing.

Python `

s = "geeksforgeeks" res = "".join([char for i, char in enumerate(s) if char not in s[:i]]) print(res)

`

**Explanation: