Rahul Patil Rahul Patil - 1 year ago 114
Python Question

Python: Best Way to remove duplicate character from string

How can I remove duplicate characters from a string using Python? For example, let's say I have a string:


How can I make the string:


I'm new to python and What I have tired and it's working. I knew there is smart and best way to do this.. and only experience can show this..

def RemoveDupliChar(Word):
NewWord = " "
index = 0
for char in Word:
if char != NewWord[index]:
NewWord += char
index += 1

NOTE: Order is important and this question is not similar to this one.

Answer Source

Using itertools.groupby:

>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download