2017-08-06 74 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当然,没问题。 –