[英]Python re.sub always matches?
我有一個看起來像這樣的數組:
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
函數的相對參數順序相同。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.