以下
>>> re.sub(r'(\d+)', r'\1' * 2, 'test line 123')
给出
'test line 123123'
有没有办法让它给出
'test line 246'
float()
强制不起作用:
>>> re.sub(r'(\d+)', float(r'\1') * 2, 'test line 123')
could not convert string to float: \1
也不是eval
或exec
。
答案 0 :(得分:5)
re.sub()
的第二个参数也可以是可调用的,可以执行以下操作:
re.sub(r'(\d+)', lambda match:'%d' % (int(match.group(1))*2), 'test line 123')
顺便说一下,确实没有理由使用float over int,因为你的正则表达式不包含句点而且总是一个非负整数
答案 1 :(得分:4)
诀窍是提供一个函数作为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'
每个匹配转换为float
,加倍,然后使用适当的格式转换为字符串。
如果数字是整数,这可以简化一点,但你的问题特别提到float
,这就是我用过的。