且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-12 21:50:34

使用 itertools.groupby:

>>>foo = "SSYYNNOOPPSSIISS">>>导入迭代工具>>>''.join(ch for ch, _ in itertools.groupby(foo))'概要'

How can I remove duplicate characters from a string using Python? For example, let's say I have a string:

foo = "SSYYNNOOPPSSIISS"

How can I make the string:

foo = SYNOPSIS

I'm new to python and What I have tired and it's working. I knew there is smart and best way to do this.. and only experience can show this..

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

NOTE: Order is important and this question is not similar to this one.

Using itertools.groupby:

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