When i changed two words in a string with other two words using re.sub i got the output. But when i tried that with numbers output is not coming correctly
当我使用re.sub改变字符串中的两个单词和其他两个单词时,我得到了输出。但是,当我尝试使用数字时输出不正确
>>> import re
>>> a='this is the string i want to change'
>>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','wanted'),a)
'this was the string i wanted to change'
>>> re.sub('(.*)is(.*)want(.*)','\\1%s\\2%s\\3' %('was','12345'),a)
'this was\x8a345 to change'
>>>
i don't know why this happens could u please tel me how to use this Thanks in advance
我不知道为什么会发生这种情况你可以提前告诉我如何使用这个谢谢
1 个解决方案
#1
7
What happens is that you're passing in the replacement r'\1was\212345\3'
, and Python cannot determine whether you want the backreference number 2, 21, 211, ... . It just picks the largest one, 212345, which is obviously not a group index in your expression. Therefore, Python decides you meant the bytestring literal b'\212'
, which is a strange way of writing the b'\x8a'
.
会发生什么事情,你传递的替换r'\ 1是\ 212345 \ 3',Python无法确定你是否需要反向引用号2,21,211,....它只选择最大的一个,212345,这显然不是表达式中的组索引。因此,Python决定你的意思是bytestring文字b'\ 212',这是一种编写b'\ x8a'的奇怪方式。
To resolve the ambiguity, use the long backreference syntax, \g<GROUP_NUMBER_HERE>
:
要解决歧义,请使用长反向引用语法\ g
>>> re.sub('(.*)is(.*)want(.*)','\\g<1>%s\\g<2>%s\\g<3>' %('was','12345'),a)
'this was the string i 12345 to change'
#1
7
What happens is that you're passing in the replacement r'\1was\212345\3'
, and Python cannot determine whether you want the backreference number 2, 21, 211, ... . It just picks the largest one, 212345, which is obviously not a group index in your expression. Therefore, Python decides you meant the bytestring literal b'\212'
, which is a strange way of writing the b'\x8a'
.
会发生什么事情,你传递的替换r'\ 1是\ 212345 \ 3',Python无法确定你是否需要反向引用号2,21,211,....它只选择最大的一个,212345,这显然不是表达式中的组索引。因此,Python决定你的意思是bytestring文字b'\ 212',这是一种编写b'\ x8a'的奇怪方式。
To resolve the ambiguity, use the long backreference syntax, \g<GROUP_NUMBER_HERE>
:
要解决歧义,请使用长反向引用语法\ g
>>> re.sub('(.*)is(.*)want(.*)','\\g<1>%s\\g<2>%s\\g<3>' %('was','12345'),a)
'this was the string i 12345 to change'