如何使用 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 不相似一个。
最佳答案
使用 itertools.groupby
:
>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
关于Python:从字符串中删除重复字符的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18799036/