您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python:如何在字符串中剪切超过2个相等字符的序列

5b51 2022/1/14 8:22:33 python 字数 1895 阅读 551 来源 www.jb51.cc/python

我正在寻找一种有效的方法来排除一个字符串,使得超过2个相同字符的所有序列在前2个之后被切断. 一些输入>输出示例是: hellooooooooo -> helloo woooohhooooo -> woohhoo 我正在循环播放角色,但它有点慢.有没有人有其他解决方案(regexp或其他) 编辑:当前代码: word_new = "" for i in range(0,len(wo

概述

一些输入>输出示例是:

hellooooooooo -> helloo
woooohhooooo -> woohhoo

我正在循环播放角色,但它有点慢.有没有人有其他解决方案(regexp或其他)

编辑:当前代码

word_new = ""
        for i in range(0,len(word)-2):    
            if not word[i] == word[i+1] == word[i+2]:
                word_new = word_new+word[i]
        for i in range(len(word)-2,len(word)):
            word_new = word_new + word[i]
import re

def ReplaceThreeOrMore(s):
    # pattern to look for three or more repetitions of any character,including
    # newlines.
    pattern = re.compile(r"(.)\1{2,}",re.DOTALL) 
    return pattern.sub(r"\1\1",s)

(这里的原始回复)
尝试这样的事情:

import re

# look for a character followed by at least one repetition of itself.
pattern = re.compile(r"(\w)\1+")

# a function to perform the substitution we need:
def repl(matchObj):
   char = matchObj.group(1)
   return "%s%s" % (char,char)

>>> pattern.sub(repl,"Foooooooooootball")
'Football'

总结

以上是编程之家为你收集整理的Python:如何在字符串中剪切超过2个相等字符的序列全部内容,希望文章能够帮你解决Python:如何在字符串中剪切超过2个相等字符的序列所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶