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
The easiest way I guess is to make use of functools.partial
, which allows you create a "partially evaluated" function:
from functools import partial
def evaluate(match, mappings):
return str(eval(match.group(0)[2:-1], mappings))
mappings = {'A': 1, 'B': 2} # Or whatever ...
newstring = sub(r'\#\{([^#]+)\}', partial(evaluate, mappings=mappings), string)