我有一个类似于:
的数组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中的行为方式不同......
答案 0 :(得分:7)
仔细查看the signature for the sub
method of compiled regexes:
sub(repl, string, count=0)
第一个参数是替换字符串,第二个参数是要操作的字符串,这与您尝试调用它的方式相反。 (请注意,这与re.sub
函数的相对参数顺序相同。)