如何使用python删除相邻重复的字母?

2024-10-01 07:19:01 发布

您现在位置:Python中文网/ 问答频道 /正文

字符串如下"hello how are you and huhuhu"

像这样"helo how are you and hu"

我试过这个正则表达式

re.sub(r'(\w)\1{1,}', r'\1', st)

这在删除一个相邻的重复字母时工作得非常好

例如"xcccc xcxcxcxc xxxxxcc"

结果是"xc xcxcxcxc xc"。在

但我希望删除一个和两个不同的相邻重复字母。在

例如"xcccc xcxcxcxc xxxxxcc",
结果必须是这样的"xc xc xc"。在

我希望这有助于理解我的问题并消除歧义。在


Tags: and字符串reyouhello字母arehow
2条回答

使用regex,您可以这样做:

import re
print (re.sub(r"(.+?)\1+", r"\1", 'hello how are you and huhuhu'))
print (re.sub(r"(.+?)\1+", r"\1", 'xcccc xcxcxcxc xxxxxcc'))

输出:

^{pr2}$

或者:

def remove_repeats(string):
    for i in range(len(string)):
        for j in range(i + 1, len(string)):
            while string[i:j] == string[j:j + j - i]:
                string = string[:j] + string[j + j - i:]
    return string


print(remove_repeats('hello how are you and huhuhu'))
print(remove_repeats('xcccc xcxcxcxc xxxxxcc'))

输出:

^{pr2}$

一种方法:

def removeDups(string):
    result = string[0]
    for i in range(1,len(string)):
        if string[i] != string[i-1]:
            result += string[i]
    return result

removeDups('hello how are you and huhuhu')

# 'helo how are you and huhuhu'

removeDups('thisss isss aaaa llloongg ssstttringgg')

# 'this is a long string'

相关问题 更多 >