Say I have strings like the following:
old_string = "I love the number 3 so much"
I would like to spot the integer numbers (in the example above, there is only one number, 3
), and replace them with a value larger by 1, i.e., the desired result should be
new_string = "I love the number 4 so much"
In Python, I can use:
r = re.compile(r'([0-9])+')
new_string = r.sub(r'\19', s)
to append a 9
at the end of the integer numbers matched. However, I would like to apply something more general on \1
.
If I define a function:
def f(i):
return i + 1
How do I apply f()
on \1
, so that I can replace the matched strings in old_string
with something like f(\1)
?
In addition to having a replace string,
re.sub
allows you to use a function to do the replacements:From the docs: