Python: how to act according to a sequence of strings

Following

>>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123') 

gives

 'test line 123123' 

is there any way to make him give

 'test line 246' 

?

float() coercion does not work:

 >>> re.sub(r'(\d+)', float(r'\1') * 2, 'test line 123') could not convert string to float: \1 

not eval or exec .

+4
source share
2 answers

The second argument to re.sub() can also be called, which allows:

 re.sub(r'(\d+)', lambda match:'%d' % (int(match.group(1))*2), 'test line 123') 

By the way, it makes no sense to use float over int, since your regular expression does not include periods and will always be a non-negative integer

+5
source

The trick is to provide a function as an argument to repl for re.sub() :

 In [7]: re.sub(r'(\d+)', lambda m:'%.0f'%(float(m.group(1))*2), 'test line 123') Out[7]: 'test line 246' 

Each match is converted to float , doubled, and then converted to string using the appropriate format.

This might be a little simplified if the number is an integer, but your question specifically mentions a float , so I used.

+4
source

Source: https://habr.com/ru/post/1392941/


All Articles