1
test1 = "<test>222</test>blah blah blah"
newVal = "222"
mstring = "(<test>).*(</test>)"
newString = re.sub(mstring,rf"\1{newVal}\2",test1)
print(newString)

I am trying to find a particular value in my string and substitute with a different string using re.sub function. Seems like i am find the correct match and replace is working however python is converting parts of the string into its ascii equivalent value. Can you help me with the above code so that i produce the below output please

<test>222</test>blah blah blah

instead i am getting below result

R2</test>blah blah blah
Krishna
  • 1,926
  • 11
  • 23

1 Answers1

2

Here is a possible solution:

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

Your approach would work with newVal being, for example, a letter:

newVal = "a"
re.sub(mstring, f'\1{newVal}\2', test1) # <test>a</test>blah blah blah

This weird behaviour is due to the fact that \1{newVal} (with newVal=333) would be interpreted as a reference to group 1333. The \g<1> syntax is equivalent to \1, but isn’t ambiguous in a replacement.

Riccardo Bucco
  • 6,551
  • 3
  • 13
  • 32