I have a list of patterns and a list of replacements. The pattern contains repeating elements but they correspond to different replacements.
txt=132GOasmHOMEwokdslNOWsdwkGO239NOW
pattern=['GO','HOME','NOW','GO','NOW']
REPLACEMENT=['why','nope','later','aha','genes']
The desired output would be 132whyasmnopewokdsllatersdwkaha239genes
What's the most efficient way to accomplish the sequential replacement?
You can loop through the two lists at the same time, and only replace the first instance of the pattern each time:
for a,b in zip(pattern,REPLACEMENT):
txt=txt.replace(a,b,1)
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