How to remove duplicate characters from a string in Python
How to remove duplicate characters from a string in Python.
Here's a step-by-step tutorial on how to remove duplicate characters from a string in Python:
Step 1: Get the input string from the user.
- You can use the
input()
function to prompt the user to enter a string.
Step 2: Initialize an empty string to store the result.
- We'll use this string to build the final string without duplicate characters.
Step 3: Iterate through each character in the input string.
- You can use a
for
loop to iterate through each character.
Step 4: Check if the character is already present in the result string.
- You can use the
in
operator to check if a character is already present. - If the character is not present, add it to the result string.
Step 5: Print or return the result string.
- After iterating through all the characters, you can either print the result string or return it from the function.
Now, let's see some code examples to illustrate these steps:
Example 1: Using a loop and an empty string
def remove_duplicates(input_string):
result = ""
for char in input_string:
if char not in result:
result += char
return result
user_input = input("Enter a string: ")
output = remove_duplicates(user_input)
print("String without duplicates:", output)
Example 2: Using set() to remove duplicates
def remove_duplicates(input_string):
return "".join(set(input_string))
user_input = input("Enter a string: ")
output = remove_duplicates(user_input)
print("String without duplicates:", output)
Example 3: Using a list comprehension
def remove_duplicates(input_string):
return "".join([char for index, char in enumerate(input_string) if char not in input_string[:index]])
user_input = input("Enter a string: ")
output = remove_duplicates(user_input)
print("String without duplicates:", output)
These are just a few examples of how you can remove duplicate characters from a string in Python. Choose the method that suits your needs the best. Feel free to modify the code according to your requirements.