Python - Remove duplicates from a String
While working with strings, there are many instances where it is needed to remove duplicates from a given string. In Python, there are many ways to achieve this.
Method 1: Remove duplicate characters without order
In the example below, a function called MyFunction is created which takes a string as an argument and converts it into a set called MySet. As in a set, elements are unordered and duplication of elements are not allowed, hence all duplicate characters will be removed in an unordered fashion. After that, the join method is used to combine all elements of MySet with an empty string.
,def MyFunction(str): MySet = set(str) NewString = "".join(MySet) return NewString MyString = "Hello Python" print(MyFunction(MyString))
The output of the above code will be:
HtPy nloeh
Method 2: Remove duplicate characters with order
In this example, an inbuilt module called collections is imported in the current script to use its one of the class called OrderedDict. The fromkeys() method of class OrderedDict is used to remove duplicate characters from the given string.
,import collections as ct def MyFunction(str): NewString = "".join(ct.OrderedDict.fromkeys(str)) return NewString MyString = "Hello Python" print(MyFunction(MyString))
The output of the above code will be:
Helo Pythn