使用正则表达式python在字符串中多次替换数字

Myj*_*jab 6 python regex string

当我使用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'
>>>
Run Code Online (Sandbox Code Playgroud)

我不知道为什么会发生这种情况你可以提前告诉我如何使用这个谢谢

phi*_*hag 8

发生的事情是你传递了替代品r'\1was\212345\3',Python无法确定你是否需要反向引用号2,21,211,.... 它只选择最大的一个,212345,这显然不是表达式中的组索引.因此,Python决定你的意思是bytestring文字b'\212',这是一种奇怪的写作方式b'\x8a'.

要解决歧义,请使用长反向引用语法\g<GROUP_NUMBER_HERE>:

>>> re.sub('(.*)is(.*)want(.*)','\\g<1>%s\\g<2>%s\\g<3>' %('was','12345'),a)
'this was the string i 12345 to change'
Run Code Online (Sandbox Code Playgroud)