Python:从字符串中删除重复字符的最佳方法
发布于 2021-01-29 18:37:09
如何使用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())
注意:顺序很重要,这个问题是不是类似于此一个。
关注者
0
被浏览
140
1 个回答
-
>>> foo = "SSYYNNOOPPSSIISS" >>> import itertools >>> ''.join(ch for ch, _ in itertools.groupby(foo)) 'SYNOPSIS'