Python Program to Remove Duplicate Characters from String

This article deals with program in Python that removes all the duplicate characters available in a given string by user at run-time.

Remove Duplicate Characters from String

The question is, write a Python program to remove duplicate characters from string. The string must be entered by user. Here is its answer:

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

strlist = []
for i in range(len(str)):
    strlist.append(str[i])

newlist = []
j = 0
for i in range(len(strlist)):
    if str[i] not in newlist:
        newlist.insert(j, str[i])
        j = j+1

print("\nOriginal String:", str)

str = ""
str = str.join(newlist)
print("New String:", str)

Here is the initial output produced by this Python program:

python remove duplicate characters from string

Now provide the input say fresherearth as string and press ENTER key to remove all the duplicate characters from the given string and print the new string like shown in the snapshot of the sample output given below:

remove duplicate characters from string python

Note - If any character occurs more than one time in given string, then all the occurrences gets considered as duplicate except the initial one.

Modified Version of Previous Program

Since in above program, the join() method was used to convert the list to string. But in this program I've done the same job using self-defined code.

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

strlist = list()
for i in range(len(str)):
    strlist.append(str[i])

newlist = list()
j = 0
for i in range(len(strlist)):
    if str[i] not in newlist:
        newlist.insert(j, str[i])
        j = j+1

print("\nOriginal String =", str)

newstr = ""
for c in newlist:
    newstr = newstr + c
print("New String =", newstr)

Here is its sample run with user input, programming:

remove duplicate characters python

Python Online Test


« Previous Program Next Program »