test1 = "<test>222</test>blah blah blah"
newVal = "222"
mstring = "(<test>).*(</test>)"
newString = re.sub(mstring,rf"\1{newVal}\2",test1)
print(newString)
我试图在字符串中查找特定值,并使用 re.sub 函数替换为不同的字符串。似乎我找到了正确的匹配项并且替换正在工作,但是 python 正在将字符串的一部分转换为其 ascii 等效值。您能帮我处理上面的代码吗,以便我生成以下输出
<test>222</test>blah blah blah
相反,我得到的结果低于
R2</test>blah blah blah
最佳答案
这是一个可能的解决方案:
test1 = "<test>222</test>blah blah blah"
newVal = "111"
mstring = "(<test>).*(</test>)"
newString = re.sub(mstring, f'\g<1>{newVal}\g<2>', test1)`
print(newString) # <test>111</test>blah blah blah
您的方法适用于 newVal
例如,一个字母:
newVal = "a"
re.sub(mstring, f'\1{newVal}\2', test1) # <test>a</test>blah blah blah
这种奇怪的行为是由于 \1{newVal}
(带有 newVal=333
)将被解释为对组 1333 的引用。 \g<1>
语法相当于 \1
,但在替换中并不含糊。
关于Python re.sub 将部分字符串更改为 ascii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58769952/