Categories
Python Answers

How to remove duplicate characters from a string with Python?

Spread the love

Sometimes, we want to remove duplicate characters from a string with Python.

In this article, we’ll look at how to remove duplicate characters from a string with Python.

How to remove duplicate characters from a string with Python?

To remove duplicate characters from a string with Python, we can use string’s join and the dict.fromkeys methods.

For instance, we write:

foo = "mppmt"
result = "".join(dict.fromkeys(foo))
print(result)

We use dict.fromkeys(foo) to get the characters in the string as keys to remove the duplicate characters and keep the characters in the same order.

Then we call join with the returned dictionary to join the characters together.

Therefore, result is 'mpt'.

Conclusion

To remove duplicate characters from a string with Python, we can use string’s join and the dict.fromkeys methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *