Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace patterns sequentially in python when pattern includes duplicates

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?

like image 446
santoku Avatar asked Aug 08 '26 02:08

santoku


1 Answers

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)
like image 181
user1763510 Avatar answered Aug 09 '26 16:08

user1763510



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!