In Python, strings are one of the most commonly used data types, and it is quite common to come across a situation where we need to remove repeated characters from a string. In this post, we will learn the different approaches to remove repeated characters from a given string in Python.
For Examples
- Input: “hello” Output: “helo”
- Input: “Mississippi” Output: “Misp”
Method 1: Using a Set and String Concatenation
In this approach, We will be using a set to store the unique characters of the string, and string concatenation to create the output string.
def remove_duplicates(s):
unique_chars = set()
output = ""
for char in s:
if char not in unique_chars:
unique_chars.add(char)
output += char
return output
string = input("Please Enter a string: ")
print(remove_duplicates(string))
Output:
Please Enter a string: programming
progamin
Method 2: Using a List and Join
In this method, we will use a list to store the all unique characters of the string. After that, we will use the join method to create the output string.
def remove_duplicates(s):
unique_chars = []
for char in s:
if char not in unique_chars:
unique_chars.append(char)
return "".join(unique_chars)
string = input("Please Enter a string: ")
print(remove_duplicates(string))
Output
Please Enter a string: hello
helo