In these programs, we will learn how to remove all the duplicate characters from a given string.
To understand these codes, you must have the knowledge of the following topics in python:
- join and append functions
- ‘in’ and ‘not in’ keywords
program 1(Without any inbuilt function)
inputstr = "Hello world" resultstr = "" for i in inputstr: if i not in resultstr: resultstr += i print(resultstr)
- First, we have declared a variable named ‘str’ and assigned it a string ‘Hello World’.
- In the next step, we have declared another variable named resultstr and assigned it an empty string. This variable will hold the result.
- We have started a loop on the string stored in str. The loop will iterate on every single character of the string Hello World.
- Inside the loop we have defined a condition to check if the current character not exist in the resultstr. If that so, we concatenate the current character to the resultstr.
- At the end we will get unique characters from str in the variable resultstr.
Program 2 (By using range function)
inputstr="Hello World" resultstr="" for i in range(len(inputstr)): if inputstr[i] not in resultstr: resultstr += inputstr[i] print(resultstr)
- First, we have Stored a string “Hello World” in a variable inputstr.
- Then, we created an empty list which we will use to store the characters that have already occurred.
- In the next statement, we have to make a loop that will start iterating from 0(i.e, the first index of the string) to the last index(which is actually 1 less than the length of the string).
- Next, we have checked whether the character present on the ith index of the string is in resultstr. If it is not, we append the character at the current index of the loop to the resultstr.
- Lastly we simply printed the resultstr.
Program 3(By using append and join functions)
inputstr= “Hello world” a= for i in inputstr: if i not in a: a.append(i) b="".join(a) print(b)
Program 4(By taking user input)
inputstr=input("Enter string: ") resultlist= for i in inputstr: if i not in resultlist: resultlist.append(i) resultstr="".join(resultlist) print(resultstr)
Enter string: Hello World