gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:17:04 24 4
gpt4 key购买 nike

我正在寻找一种有效的方法来随机生成一个字符串,以便在前 2 个字符之后截断所有超过 2 个相同字符的序列。

一些输入->输出的例子是:

hellooooooooo -> helloo
woooohhooooo -> woohhoo

我目前正在遍历字符,但速度有点慢。有没有人有其他解决方案(正则表达式或其他东西)

编辑:当前代码:

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个相等字符的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4278313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com