How to pass a variable to a re.sub callback?

后端 未结 4 1131
南笙
南笙 2021-02-09 08:29

I am using a re.sub callback to replace substrings with random values, but I would like the random values to be the same across different strings. Since the re.sub callback does

4条回答
  •  醉话见心
    2021-02-09 09:14

    You could create a closure.

    def evaluator(mappings):
      def f(match):
        return str(eval(match.group(0)[2:-1], mappings))
      return f
    
    evaluate = evaluator({'A': 1, 'B': 2})
    

    Since f is just a single statement, you could simply use lambda:

    def evaluator(mappings):
      return lambda match: str(eval(match.group(0)[2:-1], mappings))
    

提交回复
热议问题