Python Practice › String Programs › Program 35

Remove duplicate characters

EasyString Programs · 35 of 106

Write a Python program to remove duplicate characters, keeping the first occurrence of each.

Advertisement
Input
"sqatools"
Output
sqatol

Approach

  1. dict.fromkeys keeps the first occurrence in order.

Solution

Python
text = "sqatools"print("".join(dict.fromkeys(text)))
Output
sqatol

Line by line

Line 2

Dictionary keys are unique and keep insertion order, so joining them gives the de-duplicated string.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs