w3resource

Python: Remove duplicate characters of a given string


Remove duplicate characters in string.

Write a Python program to remove duplicate characters from a given string.

Visual Presentation:

Python String: Remove duplicate characters of a given string.

Sample Solution:

Python Code:

# Import the OrderedDict class from the collections module
from collections import OrderedDict

# Define a function to remove duplicate characters from a string
def remove_duplicate(str1):
    # Create an OrderedDict object to store unique characters and their order
    unique_characters = OrderedDict.fromkeys(str1)

    # Join the keys of the OrderedDict to form a string without duplicates
    return "".join(unique_characters.keys())

# Remove duplicate characters from the string "python exercises practice solution"
result1 = remove_duplicate("python exercises practice solution")
print(result1)  

# Remove duplicate characters from the string "w3resource"
result2 = remove_duplicate("w3resource")
print(result2)  

Sample Output:

python exrcisalu
w3resouc

Flowchart:

Flowchart: Remove duplicate characters of a given string

Python Code Editor:

Previous: Write a Python program to capitalize first and last letters of each word of a given string.
Next: Write a Python program to compute sum of digits of a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.