0

Is there a way to remove duplicate characters? For example if we input "hello", the output will be "helo"; another example is "overflow", the output would be "overflw"; another example "paragraphs", the output would be "parghs".

I have tried

def removeDupes(mystring):
    newStr = ""
    for ch in string:
        if ch not in newStr:
            newStr = newStr + ch
    return newStr
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
chiktin
  • 15
  • 1
  • 4
  • So what is the problem with that code? — By the way, the argument is called `mystring`, but you use `string` in the `for` loop. – Robin Krahl Oct 28 '13 at 01:32

3 Answers3

1

Change string to mystring:

def removeDupes(mystring):
    newStr = ""
    for ch in mystring:
        if ch not in newStr:
            newStr = newStr + ch
    return newStr

print removeDupes("hello")
print removeDupes("overflow")
print removeDupes("paragraphs")

>>> 
helo
overflw
parghs
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
1

yes with something called a set:

unique = set()

[ unique.add(c) for c in 'stringstring' ]
ennuikiller
  • 46,381
  • 14
  • 112
  • 137
1

I would use collections.OrderedDict for this:

>>> from collections import OrderedDict
>>> data = "paragraphs"
>>> print "".join(OrderedDict.fromkeys(data))
parghs
Ben
  • 6,687
  • 2
  • 33
  • 46