如何删除字符串中的重复字母

2024-10-01 09:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法去除重复字符?例如输入“hello”,输出为“helo”;另一个示例为“overflow”,输出为“overflow”;另一个示例“parages”,输出为“parghs”。在

我试过了

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

Tags: in示例hellofordefch字符办法
3条回答

{cd1>将用于

>>> from collections import OrderedDict
>>> data = "paragraphs"
>>> print "".join(OrderedDict.fromkeys(data))
parghs

string更改为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

是的,用的是一套:

unique = set()

[ unique.add(c) for c in 'stringstring' ]

相关问题 更多 >