[Solved] How to replace specific part of a string (replace() dosen’t help…) [closed]


I just got a trick for you to achieving what you want.

a = "hello world, hello there, hello python"
a = a.replace("hello","hi",2).replace("hi","hello",1)
print(a)

So what exactly 2nd Line does it it is replacing first two occurrence of hello to hi and then replacing 1st occurrence of hi to hello. Thus getting the output you want.

Or you can also go to other way as follows:

a = "hello world, hello there, hello python"
index = a.find("hello",2)    
a = a[:index] + a[index:].replace("hello","hi",1)
print(a)

So you can use any of them for your purpose.

solved How to replace specific part of a string (replace() dosen’t help…) [closed]