ADVERTISEMENTS

How to remove duplicates from string in python

Strings are sequences of characters enclosed in single or double quotes. They are used to store and manipulate text. Strings are immutable, meaning they cannot be changed once they are created. There are several ways to remove duplicates from a string in Python.

One way is to convert the string to a list, convert the list to a set, and then convert the set back to a string. This method utilizes the fact that sets only allow unique elements.

original_string = "hello world"

# Convert string to list
string_list = list(original_string)

# Convert list to set
string_set = set(string_list)

# Convert set to string
unique_string = ''.join(string_set)

print(unique_string)

 

Another way to remove duplicates from a string is to use a for loop to iterate through the string and use an if statement to check if the current character has already been seen.

original_string = "hello world"

unique_string = ""

for char in original_string:
    if char not in unique_string:
        unique_string += char

print(unique_string)

 

Python is a high-level, interpreted programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and more. It is known for its easy-to-read syntax and ability to handle a wide variety of programming tasks with minimal code. You can learn python from our Python Tutorials and Python Examples

ADVERTISEMENTS