如何删除字符串中重复的字母?
试过了没有成功..
def shorten_string(char_str):
new=''
for i in range(0,len(char_str)-1):
if char_str[i-1] != char_str[i]:
new += char_str[i]
return new
编辑:误解:我不想删除所有重复的字符。只要它们按顺序重复。
input: lloolleellaa
outpu: lolela
请您参考如下方法:
可以使用 groupby 删除相邻的相等项:
>>> import itertools
>>> ''.join(c[0] for c in itertools.groupby('haalllooo'))
'halo'
这只是获取每组相同项目的头部。
>>> ''.join(c[0] for c in itertools.groupby('haalllooo thheeerrree tttthhhiiisss iiisss aaann eeeexxxaaammpppllleee'))
'halo there this is an example'
只保留唯一的项目:
def unique(it):
s = set()
for x in it:
if x not in s:
s.add(x)
yield x
可以这样使用:
>>> ''.join(unique('haalllooo'))
'halo'
>>> ''.join(unique('haalllooo thheeerrree tttthhhiiisss iiisss aaann eeeexxxaaammpppllleee'))
'halo terisnxmp'
