fork download
  1. import re
  2.  
  3. def repl(m, value, counter, NumberL):
  4. counter.i += 1
  5. if counter.i in NumberL:
  6. return value
  7. return m.group()
  8.  
  9. def replace(text,key,value,NumberL):
  10. counter = lambda x: None
  11. counter.i = 0
  12. return re.sub(rf"(?!\B\w){re.escape(key)}(?<!\w\B)", lambda m: repl(m, value, counter, NumberL), text)
  13.  
  14. text = 'Suddenly you said goodbye, even though I was passionately in love with you, I hope you stay lonely and live for a hundred years'
  15. print(replace(text,'you','Cleis',[2,3]))
Success #stdin #stdout 0.03s 9320KB
stdin
Standard input is empty
stdout
Suddenly you said goodbye, even though I was passionately in love with Cleis, I hope Cleis stay lonely and live for a hundred years