【问题标题】:Python re.sub not returning expected string of intPython re.sub 未返回预期的 int 字符串
【发布时间】:2016-01-21 10:18:33
【问题描述】:

我想将零填充到字符串中的数字。例如,字符串

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 的行为不同?

【问题讨论】:

  • 你是zfilling 之前替换。您的代码相当于re.sub('(\d+)', r'000\1', 'hello120_c')。您必须使用回调,如 Wiktor 的回答,将填充推迟到您实际匹配时。
  • @tobias_k 感谢您的解释:)。

标签: python regex


【解决方案1】:

您不能直接使用反向引用。使用 lamda:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多