使用多个regex替换的python字符串

2024-04-26 02:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

当我用其他两个单词替换一个字符串中的两个单词时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'
>>>

我不知道为什么会这样,你能告诉我怎么用吗 提前谢谢


Tags: theto字符串importrestringis公司
1条回答
网友
1楼 · 发布于 2024-04-26 02:45:28

所发生的情况是,您正在传递替换的r'\1was\212345\3',而Python无法确定是否需要backreference编号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'

相关问题 更多 >