繁体   English   中英

如何使用python删除连续/一起在字符串中重复两次以上的字符?

[英]How to remove characters that repeat more than twice in a row/together in a string using python?

我们如何将像haaaaaaapppppyyyyyy这样的字符串简化为haappyy这样对于字符串中的字符,最多允许连续两次重复?

包括将---------------------转换为--的任何字符(也包括特殊字符)

我们可以使用正则表达式替换:

inp = "haaaaaaapppppyyyyyy"
output = re.sub(r'(\w)\1{2,}', r'\1\1', inp)
print(output)  # haappyy

上述逻辑匹配任何一个其后跟两次或多次的字符。 然后它只替换为两个字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM