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

问题描述 投票:0回答:3

如何从字符串中删除双连续字母?

例如:

a_str = 'hii thherre'

应该成为

'hi there'

我试着这样做:

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

但是,我得到了:

'hi ter'
python string python-3.x list-comprehension
3个回答
3
投票

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

在这种情况下,如果我理解正确,你只想采取连续相等字母的每一个序列中的一个。考虑一下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'

1
投票

您可以通过迭代所有字符及其下一个元素的组合并选择不相等的元素来完成此操作。

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

0
投票

没有进口的直蟒蛇,

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

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)
© www.soinside.com 2019 - 2024. All rights reserved.