Home  >  Article  >  Backend Development  >  How to Remove Duplicate Characters from a String in Python?

How to Remove Duplicate Characters from a String in Python?

Susan Sarandon
Susan SarandonOriginal
2024-10-19 12:46:29208browse

How to Remove Duplicate Characters from a String in Python?

Removing Duplicate Characters from a String

In Python, eliminating duplicate characters from a string is a straightforward task. When the order of the characters is irrelevant, consider the following approach:

Using a set, you can create a representation of the string with only unique characters. Subsequently, join the elements of this set back into a string using "".join(). This solution preserves the order of the characters, resulting in arbitrary ordering.

<code class="python">foo = 'mppmt'
unique_foo = "".join(set(foo))  # 'mpt'
print(unique_foo)</code>

However, if maintaining the original character order is essential, a more nuanced solution is necessary. By employing a dictionary, you can retain the insertion order of the characters.

<code class="python">foo = 'mppmt'
unique_characters = {}
for char in foo:
    unique_characters[char] = True
result = ''.join(unique_characters.keys())  # 'mpt'
print(result)</code>

This modified approach utilizes a dictionary to preserve the character order, ensuring that the resulting string maintains the same sequence.

The above is the detailed content of How to Remove Duplicate Characters from a String in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn