The following
>>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123')
gives
'test line 123123'
is there a way to make it give
'test line 246'
?
float()
coercion doesn't work:
>>> re.sub(r'(\d+)', float(r'\1') * 2, 'test line 123')
could not convert string to float: \1
nor do eval
or exec
.
The second argument to re.sub()
can also be a callable, which lets you do:
re.sub(r'(\d+)', lambda match:'%d' % (int(match.group(1))*2), 'test line 123')
BTW, there really is no reason to use float over int, as your regex does not include periods and will always be a non-negative integer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With