Given the string: s = "101010101", I would like to replace every occurrence of the pattern 010, with the pattern 0X0, so that the result should be s = "10X0X0X01".
Another similar problem is to replace the same pattern 010 with 00, so that the resulting string should be s = 100001.
So far, I tried by:
import re
s = "101010101"
s = re.sub("010", "0X0", s)
but the resulting string is 10X010X01, missing to replace the 1 in the middle.
Any help?
You can use lookarounds to find values without including them in the match:
s = re.sub(r"(?<=0)1(?=0)", "X", s)
(?<=0)1(?=0) matches a single 1 character that is preceded – (?<=…) –
and followed – (?=…) – by a zero.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With