Simply use \1
instead of $1
:
In [1]: import re
In [2]: method = 'images/:id/huge'
In [3]: re.sub(r'(:[a-z]+)', r'<span>\1</span>', method)
Out[3]: 'images/<span>:id</span>/huge'
Also note the use of raw strings (r'...'
) for regular expressions. It is not mandatory but removes the need to escape backslashes, arguably making the code slightly more readable.