我想在字符串中的数字前补零。例如,字符串
hello120_c
填充到5位数应该变成
hello00120_c
我想使用 re.sub
进行替换。这是我的代码:
>>> re.sub('(\d+)', r'\1'.zfill(5), 'hello120_c')
返回
>>> 'hello000120_c'
有 6 位而不是 5 位。单独检查 '120'.zfill(5)
会得到 '00120'
。此外,re.findall
似乎确认正则表达式匹配完整的 '120'
。
是什么导致 re.sub
行为不同?
最佳答案
您不能直接使用反向引用。使用 lambda :
re.sub(r'\d+', lambda x: x.group(0).zfill(5), 'hello120_c')
# => hello00120_c
另请注意,您不需要捕获组,因为您可以通过 .group(0)
访问匹配的值。另外,请注意用于声明正则表达式的 r'...'
(原始字符串文字)。
参见 IDEONE demo :
import re
res = re.sub(r'\d+', lambda x: x.group(0).zfill(5), 'hello120_c')
print(res)
关于Python re.sub 没有返回预期的 int 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920943/