Python: how to substitute and know whether it matched

前端 未结 3 465
温柔的废话
温柔的废话 2021-01-05 00:53

I know that re.sub(pattern, repl,text) can substitute when pattern matches, and then return the substitute.

My code is:

text = re.sub(p         


        
3条回答
  •  鱼传尺愫
    2021-01-05 01:27

    The repl parameter can also be a function which takes an RE match object and returns what the replacement should be; this function is not called if the text doesn't match. You could use that to do what you needed then just return a constant string you want to replace it with. This would cut down on an unneeded second check against the RE.

提交回复
热议问题