w3resource

Python: Remove duplicate words from a given string

Python String: Exercise-90 with Solution

Remove duplicate words in string.

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

Sample Solution:

Python Code:

# Define a function to return a string with unique words
def unique_list(text_str):
    # Split the input string into a list of words
    l = text_str.split()
    
    # Initialize an empty list to store unique words
    temp = []
    
    # Iterate through each word in the list
    for x in l:
        # Check if the word is not already in the temporary list
        if x not in temp:
            # If true, add the word to the temporary list
            temp.append(x)
    
    # Join the unique words into a string and return the result
    return ' '.join(temp)

# Initialize a string
text_str = "Python Exercises Practice Solution Exercises"

# Print the original string
print("Original String:")
print(text_str)

# Print a newline for better formatting
print("\nAfter removing duplicate words from the said string:")

# Call the function to remove duplicate words and print the result
print(unique_list(text_str)) 

Sample Output:

Original String:
Python Exercises Practice Solution Exercises

After removing duplicate words from the said string:
Python Exercises Practice Solution

Flowchart:

Flowchart: Remove duplicate words from a given string.

Python Code Editor:

Previous: Write a Python program to remove unwanted characters from a given string.
Next: Write a Python program to convert a given heterogeneous list of scalars into a string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/string/python-data-type-string-exercise-90.php