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 variant I would recommend:
mappings = {'A': 1, 'B': 2} # Or whatever ... def evaluate(match): return str(eval(match.group(0)[2:-1], mappings)) newstring = sub(r'\#\{([^#]+)\}', evaluate, string)
i.e. simply put the def evaluate(..) just before the sub(), as a local function.
def evaluate(..)
sub()