首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用python删除相邻重复的字母?

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

Stack Overflow用户
提问于 2018-06-27 20:31:24
回答 2查看 318关注 0票数 -5

字符串作为此"hello how are you and huhuhu"

要作为此"helo how are you and hu"

我尝试过这个正则表达式,

代码语言:javascript
复制
re.sub(r'(\w)\1{1,}', r'\1', st)

在删除一个相邻的重复字母时,这是非常好的

例如"xcccc xcxcxcxc xxxxxcc"

结果是"xc xcxcxcxc xc"

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

例如"xcccc xcxcxcxc xxxxxcc",

结果必须是这样的"xc xc xc"

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

EN

回答 2

Stack Overflow用户

发布于 2019-07-23 20:56:09

使用regex,您可以像这样做:

代码语言:javascript
复制
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'))

输出:

代码语言:javascript
复制
helo how are you and hu
xc xc xc

或者:

代码语言:javascript
复制
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'))

输出:

代码语言:javascript
复制
helo how are you and hu
xc xc xc
票数 0
EN

Stack Overflow用户

发布于 2018-06-27 20:42:24

一种方法是:

代码语言:javascript
复制
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'
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51062873

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档