Remove Duplicates from Python String, Keep Order

You can use list comprehensions and sets to remove duplicates while maintaining the original order. The specific steps are as follows:

  1. Convert the string into a list.
  2. Utilize list comprehension and set to remove duplicates while preserving the original order.
  3. Convert the deduplicated list back to a string.

The sample code is as follows:

s = "abacdbefgh"
unique_chars = "".join(ch for ch in s if ch not in set(s.replace(" ","")))
print(unique_chars)

This will remove duplicates and maintain the original order of the string as “acdbefgh”.

bannerAds