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 exampl
In addition to having a replace string, re.sub
allows you to use a function to do the replacements:
>>> import re
>>> old_string = "I love the number 3 so much"
>>> def f(match):
... return str(int(match.group(1)) + 1)
...
>>> re.sub('([0-9])+', f, old_string)
'I love the number 4 so much'
>>>
From the docs:
re.sub(pattern, repl, string, count=0, flags=0)
If
repl
is a function, it is called for every non-overlapping occurrence ofpattern
. The function takes a single match object argument, and returns the replacement string.