Python replace string pattern with output of function

You can pass a function to re.sub. The function will receive a match object as the argument, use .group() to extract the match as a string.

>>> def my_replace(match):
...     match = match.group()
...     return match + str(match.index('e'))
...
>>> string = "The quick @red fox jumps over the @lame brown dog."
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

Leave a Comment