阅读背景:

Python:如何对re的匹配字符串进行操作

来源:互联网 

The following

>>> re.sub(r'(\d+)', r'

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:

float()强制不起作用:

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

nor do eval or exec.

也不是eval或exec。

2 个解决方案

#1


5  

The second argument to re.sub() can also be a callable, which lets you do:

re.sub()的第二个参数也可以是可调用的,它允许您执行:

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

顺便说一下,确实没有理由使用float over int,因为你的正则表达式不包含句点而且总是一个非负整数

#2


4  

The trick is to supply a function as the repl argument to re.sub():

诀窍是提供一个函数作为re.sub()的repl参数:

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.

每个匹配都转换为float,doubled,然后使用适当的格式转换为字符串。

This can be simplified a little bit if the number is integer, but your question specifically mentions float, so that's what I've used.

如果数字是整数,这可以简化一点,但你的问题特别提到浮点数,所以这就是我用过的。


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

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:

float()强制不起作用:

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

nor do eval or exec.

也不是eval或exec。

2 个解决方案

#1


5  

The second argument to re.sub() can also be a callable, which lets you do:

re.sub()的第二个参数也可以是可调用的,它允许您执行:

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

顺便说一下,确实没有理由使用float over int,因为你的正则表达式不包含句点而且总是一个非负整数

#2


4  

The trick is to supply a function as the repl argument to re.sub():

诀窍是提供一个函数作为re.sub()的repl参数:

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.

每个匹配都转换为float,doubled,然后使用适当的格式转换为字符串。

This can be simplified a little bit if the number is integer, but your question specifically mentions float, so that's what I've used.

如果数字是整数,这可以简化一点,但你的问题特别提到浮点数,所以这就是我用过的。


' * 2,



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: