0

A list below and I want to replace the 2nd occurrence of the 'pen' with 'his' in the list:

the_list = ['pen has pen cap', 'pen has pen ink', 'pen has pen attitude']

referencing here:

def replace_second(string, a, b):
   return string.replace(a, b, 2).replace(b, a, 1)        # replace the 2nd occurrence 
   #return string.replace(b, a, 2).replace(a, b, 1)       # replace the 1st occurrence

new_list = [replace_second(t, 'pen', 'his') for t in the_list]

Output:

['pen has his cap', 'pen has his ink', 'pen has his attitude']

What would be a better/quicker way? Thank you.

And, inspired by @Keyur Potdar and @AMC, another way could be:

n = 2

for t in the_list:
    print (t.replace('pen','$$$',n-1).replace('pen','his',1).replace('$$$','pen'))

# pen has his cap
# pen has his ink
# pen has his attitude
Mark K
  • 8,767
  • 14
  • 58
  • 118
  • 1
    Have a look at [this question](https://stackoverflow.com/questions/27589325/how-to-find-and-replace-nth-occurrence-of-word-in-a-sentence-using-python-regula). – Keyur Potdar Feb 13 '20 at 04:10
  • 2
    Does this answer your question? [How to find and replace nth occurrence of word in a sentence using python regular expression?](https://stackoverflow.com/questions/27589325/how-to-find-and-replace-nth-occurrence-of-word-in-a-sentence-using-python-regula) – AMC Feb 13 '20 at 04:13
  • 1
    @Keyur Potdar, thank you! love the 1-liner! – Mark K Feb 13 '20 at 04:16
  • @AMC, thank you! it's the same link as Keyur Potdar pointed. – Mark K Feb 13 '20 at 04:17

0 Answers0