Python回复sub总是匹配?

2024-06-24 11:53:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组,看起来像:

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 ]

我希望newlist是:

[
  "blah blah",
  "\nbarnacles and stuff()",
  "\n",
  "\nother stuff )"
]

相反,我得到了:

[
  "",
  "",
  "",
  ""
]

怎么回事?这在REPL中表现不一样。。。你知道吗


Tags: andrehello数组rxblahthingcompile
1条回答
网友
1楼 · 发布于 2024-06-24 11:53:21

仔细看the signature for the ^{} method of compiled regexes

sub(repl, string, count=0)

第一个参数是替换字符串,第二个参数是要对其进行操作的字符串,这与您试图调用它的方式相反。(请注意,这与^{}函数的相对参数顺序相同。)

相关问题 更多 >