Remove all duplicates from a given string in Python

Remove all duplicates from a given string in Python

To remove all duplicates from a given string in Python, you can use a combination of string manipulation and data structures like set or ordered dictionary.

Here are a few methods to accomplish this:

  1. Using Set: This method doesn't maintain the order of characters.

    s = "geeksforgeeks" result = "".join(set(s)) print(result) # It might print something like "gfroekes" because order is not preserved. 
  2. Using OrderedDict: OrderedDict from the collections module will help maintain the order of characters.

    from collections import OrderedDict s = "geeksforgeeks" result = "".join(OrderedDict.fromkeys(s)) print(result) # Outputs: "geksfor" 
  3. Using a Loop: You can manually check for the existence of a character in the result string and build the string accordingly.

    s = "geeksforgeeks" result = "" for char in s: if char not in result: result += char print(result) # Outputs: "geksfor" 

Among these methods, using an OrderedDict is efficient when order matters because it internally maintains the order of insertion and ensures that no duplicates are added.


More Tags

pom.xml git-difftool intervention app-store procedure kotlin-interop md5 3d spring-transactions css-reset

More Programming Guides

Other Guides

More Programming Examples