How to use python regex to replace using captured group? [duplicate]

You need to escape your backslash:

p.sub('gray \\1', s)

alternatively you can use a raw string as you already did for the regex:

p.sub(r'gray \1', s)

Leave a Comment