Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to act on re's matched string

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.

like image 897
Adobe Avatar asked Jan 18 '23 16:01

Adobe


1 Answers

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

like image 175
Dor Shemer Avatar answered Jan 20 '23 05:01

Dor Shemer