How can I remove duplicate characters from a string using Python? For example, let’s say I have a string:
foo = 'mppmt'
How can I make the string:
foo = 'mpt'
NOTE: Order is not important
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If order does not matter, you can use
set()will create a set of unique letters in the string, and"".join()will join the letters back to a string in arbitrary order.If order does matter, you can use a
dictinstead of a set, which since Python 3.7 preserves the insertion order of the keys. (In the CPython implementation, this is already supported in Python 3.6 as an implementation detail.)resulting in the string
"mpt". In earlier versions of Python, you can usecollections.OrderedDict, which has been available starting from Python 2.7.