Remove Duplicate Characters in a string python

Last Updated On Friday 27th Aug 2021

python remove duplicates from string

Example 1

	text = "hhhhttttmmmmhhhtttllllhhh"
print(f"before: {text}")

corrected = ""

charSet = set()
for c in text:
    if c not in charSet:
        charSet.add(c)
        corrected = c

text = corrected
print(f"after:  {text}")
	

Example 2

	foo = 'hhttmmmmmmmll'
corrected = ''.join(sorted(set(foo), key=foo.index))

print(corrected) # html
	

Example 3

	import re

word = "tttthhhiiisss iiisss aaann eeeexxxaaammpppllleee"

print(re.compile(r'(.)\1{1,}', re.IGNORECASE).sub(r'\1',word))