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

Rah*_*til 12 python string text-processing

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

foo = "SSYYNNOOPPSSIISS"
Run Code Online (Sandbox Code Playgroud)

我该如何制作字符串:

foo = SYNOPSIS
Run Code Online (Sandbox Code Playgroud)

我是python的新手,我已经厌倦了,而且它正在工作.我知道有聪明和最好的方法来做到这一点......只有经验可以证明这一点..

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

注意:顺序很重要,这个问题是不是类似于一个.

fal*_*tru 19

使用itertools.groupby:

>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
Run Code Online (Sandbox Code Playgroud)

  • @RahulPatil它通常在循环中用作占位符名称.你永远不会使用它,但它被放在那里因为你需要放东西.`itertools.groupby`是标准库中itertools模块的一部分.在falsetru的答案中有一个链接 (2认同)