2014-04-28 70 views
0

我有一個重複連續的昏迷字符串,我想在昏迷之間插入一個字符,例如零。當我運行應用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' 

我明白爲什麼它正在發生的事情,那裏的被重疊模式,但我不知道如何解決它。

回答

2

您可以使用一個超前匹配後跟另一個逗號一個逗號,並與",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' 
+0

短而甜。 :) – zx81

+0

看起來,只是我想念,謝謝 – supita

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'