Python replace string pattern with output of function
python, regex
Solution
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.'
Problem
I have a string in Python, say `The quick @red fox jumps over the @lame brown dog.` I'm trying to replace each of the words that begin with `@` with the output of a function that takes the word as an argument. ``` def my_replace(match): return match + str(match.index('e')) #Psuedo-code string = "The quick @red fox jumps over the @lame brown dog." string.replace('@%match', my_replace(match)) # Result "The quick @red2 fox jumps over the @lame4 brown dog." ``` Is there a clever way to do this?