Python:从字符串中删除重复字符的最佳方法

2024-04-19 23:41:08 发布

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

如何使用Python从字符串中删除重复字符?例如,假设我有一个字符串:

foo = "SSYYNNOOPPSSIISS"

我该怎么做绳子:

foo = SYNOPSIS

我对python很陌生,我已经厌倦了,它正在工作。我知道有一个聪明的最好的方法。。只有经验才能证明这一点。。

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

注意:顺序很重要,这个问题与this问题不同。


Tags: 方法字符串证明indexfoodef经验字符
3条回答

这个怎么样:

oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
    if char != newstring[-1]:
        newstring += char    

这是一个不导入itertools的解决方案:

foo = "SSYYNNOOPPSSIISS"
''.join([foo[i] for i in range(len(foo)-1) if foo[i+1]!= foo[i]]+[foo[-1]])

Out[1]: 'SYNOPSIS'

但它比其他方法慢!

使用^{}

>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'

相关问题 更多 >