我有一个看起来像这样的数组:
mylist = [ "blah blah hello", "\nbarnacles and stuff()", "\nhello again", "\nother stuff )" ]
我的正则表达式如下:
s = 'hello' rx = re.compile(s + '.*') newlist = [ rx.sub(thing, '') for thing in mylist ]
我期待新名单:
[ "blah blah", "\nbarnacles and stuff()", "\n", "\nother stuff )" ]
相反,我得到了:
[ "", "", "", "" ]
这是怎么回事?这在REPL中的行为方式不同......
仔细查看已编译正则表达式方法的签名sub
:
sub(repl, string, count=0)
第一个参数是替换字符串,第二个参数是要操作的字符串,这与您尝试调用它的方式相反.(注意,这与re.sub
函数的相对参数顺序相同.)