Reputation: 651
I know that in Python you can find and replace with
re.sub('(b)','\\1BB','abc')
But, how would you proceed, if you wanted more processing, like you get a single digit number and you add x to it?
I'd have not problem doing it with a function and slicing and pasting the original string into a new one, with the regex matching pattern changed, but what is the simplest way of doing it?
Upvotes: 1
Views: 71
Reputation: 103874
You can call a function rather than a simple replacement string in re.sub:
>>> re.sub('(\d+)',
... lambda x: ' {}+3={} '.format(x.group(1),int(x.group(1))+3),
... 'a12c')
'a 12+3=15 c'
Or,
def r(m):
return ' {}+{}={} '.format(m.group(1),m.group(2),
int(m.group(1))+int(m.group(2)))
>>> print re.sub('(\d)(\d)',r,'a12c')
'a 1+2=3 c'
Upvotes: 2