【问题标题】:strange execution of re.sub() in python在 python 中奇怪地执行 re.sub()
【发布时间】:2015-03-03 17:44:39
【问题描述】:

考虑以下执行。

Python 2.7.2 (default, Sep 19 2012, 01:44:39)
[GCC 4.2.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> old_value=1
>>> new_value=2
>>> re.sub('0x(..)'+format(old_value, '02x'), '0x\\1x'+format(new_value, '02x'), '0xab01')
'0xabx02'
>>> re.sub('0x(..)'+format(old_value, '02x'), '0x\\1'+format(new_value, '02x'), '0xab01')
'0xB'

所以基本上,我试图修改一个十六进制值,但只有两个最低有效数字。在此示例中,如果输入字符串中存在“02”,我尝试将“01”替换为“02”。 第一次 re.sub() 调用的输出是预期的。但是,我完全无法理解第二次调用的输出(这当然是我想做的)。这让我困惑了很长时间,我倾向于问这可能是一个 python 错误吗?还是我在这里遗漏了什么?

【问题讨论】:

    标签: python regex string-substitution


    【解决方案1】:

    '0x\\1'+format(new_value, '02x')'0x\\102',Python 将 \\102 视为单个转义序列。因为恰好有三个八进制数字,所以它被视为八进制转义(而不是对组 102 的引用),并且八进制 102 是字符 B。要解决这个问题,请写'0x\\g<1>'+format(new_value, '02x')

    【讨论】:

      猜你喜欢
      • 2020-08-27
      • 1970-01-01
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-30
      相关资源
      最近更新 更多