Consider this simple MWE:
s = 'foo bar bar'
I'd like to use re.sub
to change this to, say:
t = 'foo1 bar1 bar1'
If I wanted to append a suffix X
, this would be pretty simple:
re.sub(r'(\w+)\b', r'\1{}'.format('X'), s)
'fooX barX barX'
However, the problem arises when I try to substitute numbers:
re.sub(r'(\w+)\b', r'\1{}'.format(1), s)
Because this gives an error: invalid group reference
. Now, I understand why this is the case - the number is inserted into the string, and the string becomes '\11'
which would refer to an invalid capture group.
Is there a way to use re.sub
and get this working?
Note that this is just a simple example, and I'm not looking for an alternate solution.