Python:从字符串中删除重复字符的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18799036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Best Way to remove duplicate character from string
提问by Rahul Patil
How can I remove duplicate characters from a string using Python? For example, let's say I have a string:
如何使用 Python 从字符串中删除重复字符?例如,假设我有一个字符串:
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..
我是 python 的新手,我累了,它正在工作。我知道有一个聪明和最好的方法来做到这一点..只有经验才能证明这一点..
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 thisone.
注意:顺序很重要,这个问题是不是类似于此一个。
采纳答案by falsetru
Using itertools.groupby
:
>>> foo = "SSYYNNOOPPSSIISS"
>>> import itertools
>>> ''.join(ch for ch, _ in itertools.groupby(foo))
'SYNOPSIS'
回答by G M
This is a solution without importing itertools:
这是一个不导入 itertools 的解决方案:
foo = "SSYYNNOOPPSSIISS"
''.join([foo[i] for i in range(len(foo)-1) if foo[i+1]!= foo[i]]+[foo[-1]])
Out[1]: 'SYNOPSIS'
But it is slower than the others method!
但它比其他方法慢!
回答by jtu
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)
回答by Elliott
How about this:
这个怎么样:
oldstring = 'SSSYYYNNNOOOOOPPPSSSIIISSS'
newstring = oldstring[0]
for char in oldstring[1:]:
if char != newstring[-1]:
newstring += char
回答by rrao
How about
怎么样
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)
回答by Esptheitroad Murhabazi
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")
I've discover that solution with itertools and with list comprehesion even the solution when we compare the char to the last element of the list doesn't works
我发现使用 itertools 和 list comprehesion 的解决方案甚至当我们将字符与列表的最后一个元素进行比较时的解决方案也不起作用
回答by mohit Kumar
You can try this:
你可以试试这个:
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))