python - 如何使用python删除相邻重复的字母?
问题描述
像这样的字符串"hello how are you and huhuhu"
成为这样 "helo how are you and hu"
我试过这个正则表达式,
re.sub(r'(\w)\1{1,}', r'\1', st)
这在删除一个相邻的重复字母时效果很好
比如 "xcccc xcxcxcxc xxxxxcc"
,
结果是"xc xcxcxcxc xc"
。
但我希望删除一个和两个不同的相邻重复字母。
例如 "xcccc xcxcxcxc xxxxxcc",
结果必须是这样的"xc xc xc"
。
我希望这有助于理解我的问题并消除歧义。
解决方案
使用正则表达式,您可以这样做:
import re
print (re.sub(r"(.+?)\1+", r"\1", 'hello how are you and huhuhu'))
print (re.sub(r"(.+?)\1+", r"\1", 'xcccc xcxcxcxc xxxxxcc'))
输出:
helo how are you and hu
xc xc xc
或者:
def remove_repeats(string):
for i in range(len(string)):
for j in range(i + 1, len(string)):
while string[i:j] == string[j:j + j - i]:
string = string[:j] + string[j + j - i:]
return string
print(remove_repeats('hello how are you and huhuhu'))
print(remove_repeats('xcccc xcxcxcxc xxxxxcc'))
输出:
helo how are you and hu
xc xc xc
推荐阅读
- amazon-web-services - AWS Workspace 安全组出口要求
- typescript - 打字稿:理解联合和交叉类型
- wpf - WPF 在特定列上启动 Datagrid Interaction.Triggers
- c++ - 存储二进制文件的最佳方式是什么
- python - 在 Python 中使用多个对象解析 JSON
- reactjs - 材质 UI 选择覆盖主题中的位置
- javascript - Node.js Express 输入验证“:”之间的两个字符串被接受
- node.js - Angular 与 Oracle
- python - Socket IO 连接自动关闭
- python - Django url 显示错误:未解析的引用