Python:如何在字符串中剪切超过2个相等字符的序列
发布时间:2021-01-24 03:33:45 所属栏目:Python 来源:互联网
导读:我正在寻找一种有效的方法来排除一个字符串,使得超过2个相同字符的所有序列在前2个之后被切断. 一些输入输出示例是: hellooooooooo - helloowoooohhooooo - woohhoo 我正在循环播放角色,但它有点慢.有没有人有其他解决方案(regexp或其他) 编辑:当前代码: w
我正在寻找一种有效的方法来排除一个字符串,使得超过2个相同字符的所有序列在前2个之后被切断. 一些输入>输出示例是: 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"11",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' (编辑:甘南站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- CentOS中使用virtualenv搭建python3环境
- 如何重定向到DJANGO中包含非ascii字符的查询字符串URL?
- Pythonic计算pandas数据帧条纹的方法
- Python:如何在字符串中剪切超过2个相等字符的序列
- 如何执行python命令行自动完成,但不仅仅是在字符串的开头
- python – 有没有办法指定py2exe的build目录
- python实现数值积分的Simpson方法实例分析
- 在Python Celery中,如何在连续的工作调用中持久保存对象?
- 在cygwin下,如何配置Mercurial以使用WinMerge进行合并?
- flask:wsgi-middleware vs before_和after_request()