Подтвердить что ты не робот

Python: лучший способ удалить повторяющийся символ из строки

Как удалить повторяющиеся символы из строки с помощью 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()) 

ПРИМЕЧАНИЕ. Порядок важен, и этот вопрос не похож на этот.

4b9b3361

Ответ 1

Использование itertools.groupby:

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

Ответ 2

Это решение без импорта itertools:

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

Out[1]: 'SYNOPSIS'

Но он медленнее, чем метод других!

Ответ 3

Как насчет этого:

oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
    if char != newstring[-1]:
        newstring += char    

Ответ 4

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 с последним элементом списка, не работает

Ответ 5

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)  

Ответ 6

Как насчет

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)

Ответ 7

Вы можете попробовать это:

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))