12

如何使用 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()) 

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

4

7 回答 7

20

使用itertools.groupby

>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
于 2013-09-14T06:32:40.737 回答
4

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

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

Out[1]: 'SYNOPSIS'

但它比其他方法慢!

于 2013-09-14T07:25:45.623 回答
2

这个怎么样:

oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
    if char != newstring[-1]:
        newstring += char    
于 2015-04-03T00:24:49.433 回答
1
def remove_duplicates(astring):
  if isinstance(astring,str) :
    #the first approach will be to use set so we will convert string to set and then convert back set to string and compare the lenght of the 2
    newstring = astring[0]
    for char in astring[1:]:
        if char not in newstring:
            newstring += char    
    return newstring,len(astring)-len(newstring)
  else:
raise TypeError("only deal with alpha  strings")

我发现使用 itertools 和列表理解的解决方案即使我们将 char 与列表的最后一个元素进行比较时的解决方案也不起作用

于 2017-07-15T08:48:01.190 回答
0
def removeDuplicate(s):  
    if (len(s)) < 2:
        return s

    result = []
    for i in s:
        if i not in result:
            result.append(i)

    return ''.join(result)  
于 2014-10-22T09:58:56.280 回答
0

怎么样

foo = "SSYYNNOOPPSSIISS"


def rm_dup(input_str):
    newstring = foo[0]
    for i in xrange(len(input_str)):
        if newstring[(len(newstring) - 1 )] != input_str[i]:
            newstring += input_str[i]
        else:
            pass
    return newstring

print rm_dup(foo)
于 2016-11-15T12:03:53.960 回答
-1

你可以试试这个:

string1 = "example1122334455"
string2 = "hello there"

def duplicate(string):
    temp = ''

    for i in string:
        if i not in temp: 
            temp += i

    return temp;

print(duplicate(string1))
print(duplicate(string2))
于 2019-10-20T10:50:01.453 回答