gpt4 book ai didi

python - 替换Python中重复的连续字符

转载 作者:行者123 更新时间:2023-11-28 19:52:26 26 4
gpt4 key购买 nike

我需要制作一个函数,用单个字符替换重复的、连续的字符,例如:

 'hiiii how are you??' -> 'hi how are you?'
'aahhhhhhhhhh whyyyyyy' -> 'ah why'
'foo' -> 'fo'
'oook. thesse aree enoughh examplles.' -> 'ok. these are enough examples'

最佳答案

你可以试试像(.)\1+这样的正则表达式,即“something, then more of the same something”,并将其替换为\1,即“第一件事”。

>>> import re
>>> re.sub(r"(.)\1+", r"\1", 'aahhhhhhhhhh whyyyyyy')
'ah why'
>>> re.sub(r"(.)\1+", r"\1", 'oook. thesse aree enoughh examplles.')
'ok. these are enough examples.'

使用 functools.partial(或您喜欢的任何其他方式)使其成为一个函数

>>> import functools
>>> dedup = functools.partial(re.sub, r"(.)\1+", r"\1")
>>> dedup('oook. thesse aree enoughh examplles.')
'ok. these are enough examples.'

关于python - 替换Python中重复的连续字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54571132/

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