我有一个重复连续昏迷的字符串,我想在昏迷之间插入一个字符,例如零。当我运行re.sub它返回的是:
re.sub(r",,", ",0," , "a,,,,,,,,,,,,,a",)
'a,0,,0,,0,,0,,0,,0,,a'
我想要的结果是所有的替换,例如:
'a,0,0,0,0,0,0,0,0,0,0,0,0,a'
我理解为什么会发生这种情况,模式中存在重叠,但我不知道如何修复它。
答案 0 :(得分:3)
您可以使用前瞻匹配逗号后跟另一个逗号,并将匹配替换为",0"
,例如:
>>> re.sub(r",(?=,)", ",0", "a,,,,,,,,,,,,,a")
'a,0,0,0,0,0,0,0,0,0,0,0,0,a'
或者没有正则表达式:
>>> ",".join(x or "0" for x in "a,,,,,,,,,,,,,a".split(","))
'a,0,0,0,0,0,0,0,0,0,0,0,0,a'
答案 1 :(得分:0)
这实现了预期的结果:
In [1]: re.sub(r",,", ",0,0" , "a,,,,,,,,,,,,,a",)
Out[1]: 'a,0,0,0,0,0,0,0,0,0,0,0,0,a'