2017-08-06 76 views
0

我有一個正則表達式<type '_sre.SRE_Pattern'>,我想用另一個字符串替換匹配的字符串。以下是我有:使用編譯對象的Python正則表達式

compiled = re.compile(r'some regex expression') 
s = 'some regex expression plus some other stuff' 
compiled.sub('substitute', s) 
print(s) 

s

'substitute plus some other stuff' 

然而,我的代碼不能正常使用的串並沒有改變。

回答

1

re.sub不是就地操作。從該文檔:

返回由替換REPL替換串中最左邊的非重疊 發生圖案所獲得的字符串。

因此,您必須將返回值分配回a

... 
s = compiled.sub('substitute', s) 
print(s) 

這給

'substitute plus some other stuff' 

正如你所期望。

+0

哦,它的工作。謝謝。 ! –

+0

@ChrisJohnson當然,沒問題。 –