Python Program to Remove Duplicate Words from String

This article deals with program in Python that removes all duplicate words from given string. All words that occurs more than one time in a string considered as duplicate except its initial or first occurrence.

Remove Duplicate Words from String

The question is, write a Python program to delete duplicate words from a string. The string must be entered by user at run-time. Here is its answer:

print("Enter the String: ")
str = input()

old_word_list = str.split()
new_word_list = []
j = 0

for i in range(len(old_word_list)):
    if old_word_list[i] not in new_word_list:
        new_word_list.insert(j, old_word_list[i])
        j = j+1

new_str = ""
for i in range(len(new_word_list)):
    new_str = new_str + new_word_list[i] + " "

print("\nNew String =", new_str)

Here is the snapshot of initial output produced by above program:

python remove duplicate words from string

Now supply the input say hello how are hello are hello you and press ENTER key to remove all duplicate words from given string like shown in the sample output given below:

remove duplicate words from string python

Modified Version of Previous Program

I've said this program as the modified version of previous program, because this program includes some extra features like displaying message according to the availability of duplicate words. That is, I've included three separate messages in all three cases such as when no duplicate found, only 1 duplicate found, and multiple duplicate words found. Let's have a look at the program and its sample run to understand it in a clear way:

print("Enter the String: ", end="")
str = input()

old_word_list = str.split()
new_word_list = []
j = 0
count = 0

for i in range(len(old_word_list)):
    if old_word_list[i] not in new_word_list:
        new_word_list.insert(j, old_word_list[i])
        j = j+1
    else:
        count = count+1

new_str = ""
for i in range(len(new_word_list)):
    new_str = new_str + new_word_list[i] + " "

if count==0:
    print("\nNo duplicate word found!")
elif count==1:
    print("\nA single duplicate word found and removed successfully!")
    print("\nNow the new string =", new_str)
else:
    print("\nTotal", count, "duplicate words found and removed successfully!")
    print("\nNow the new string =", new_str)

The snapshot given below shows the sample run of above program after providing exactly same input as of previous program's sample run:

remove all duplicate words from string python

Python Online Test


« Previous Program Next Program »


Liked this post? Share it!