繁体   English   中英

给定一个字符串,如何删除所有重复的连续字母?

[英]Given a string how can I remove all the duplicated consecutive letters?

如何从字符串中删除两个连续的字母?

例如:

a_str = 'hii thherre'

应该成为

'hi there'

我试图做:

a_str = ''.join(sorted(set(a_str), key=a_str.index))

但是,我得到:

'hi ter'

是的,也可以考虑 [三个或四个连续字母]

在这种情况下,如果我理解正确,您只想从每个连续相等的字母序列中取一个。 考虑itertools.groupby

>>> from itertools import groupby
>>> a_str = 'hii thherre'
>>> ''.join(k for k, _ in groupby(a_str))
'hi there'

编辑:奖金正则表达式

>>> import re
>>> re.sub(r'(.)\1*', r'\1', a_str)
'hi there'

您可以通过迭代所有字符及其下一个元素的组合并选择不相等的组合来做到这一点。

from itertools import zip_longest

a_str = 'hii thherre'
new_a = ''.join(i[0] for i in zip_longest(a_str, a_str[1:]) if i[0] != i[1])

print(new_a) # -> hi there

没有进口的直蟒蛇,

拆分字符串并检查下一个字符是否相同,如果是,则将其删除。

a_str = 'hii thherre'
e = list(a_str)
b_str = ""
for i, x in enumerate(e):
    nextelem = e[(i + 1) % len(e)]
    if nextelem == x:
        print("Duplicate found, removing")
    else:
        b_str = b_str + x

print(b_str)

另一个纯 Python 版本,函数式风格:

import operator

getter = operator.itemgetter(1)
it = iter(s)
result = next(it) + ''.join(map(getter, filter(lambda x: x[0] != x[1], zip(s, it))))

或者,避免导入:

it = iter(s)
result = next(it) + ''.join(map(lambda x: x[1], filter(lambda x: x[0] != x[1], zip(s, it))))

简单的方法,使用带有if-condition 的for 循环

a_str = 'hii thherre'
s = a_str[0]
for i in range(1, len(a_str)):
    if(a_str[i-1] != a_str[i]): s += a_str[i]
print(s) #hi there

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM