2

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.

cs95
  • 274,032
  • 76
  • 480
  • 537
  • Wow, that is a simple solution, thanks. – cs95 Nov 14 '17 at 18:53
  • 1
    I recently [answered a question for JavaScript](https://stackoverflow.com/questions/46456706/escaping-numerals-in-string-replace/46457192#46457192) that had the same issue. You can create a callback function like [this](https://stackoverflow.com/questions/3218283/how-to-pass-a-variable-to-a-re-sub-callback) or [this](https://stackoverflow.com/questions/2094975/python-re-sub-question) – ctwheels Nov 14 '17 at 18:53
  • You can also try this, it worked for me: `final_s = re.sub('\s(?=\w)|$', '1 ', s)[:-1]` with output of `'foo1 bar1 bar1'` – Ajax1234 Nov 14 '17 at 18:59

0 Answers0