+ 1

how to Replace only second similar string(eg: go with chill) don’t use replace twice.

msg = "let go out & go tonight" print (msg.replace("go", "chill")

16th Sep 2020, 10:28 AM
Kesava N
Kesava N - avatar
7 odpowiedzi
+ 3
Here is a try, that can do the job. First the input text is split() to words. Also it creates a list with the indexes that occur for the word to replace. The replacement is not done with str.replace(...), but with an index for n-th occurrence. This means, you can replace one occurrence, that can be the 1. , 2. , 3., ... msg_split = "let go out & go tonight".split() old_word = 'go' new_word = 'chill' occr_to_repl = 2 idx = [i for i,e in enumerate(msg_split) if e == old_word] msg_split[idx[occr_to_repl -1]] = 'chill' print(' '.join(msg_split))
19th Sep 2020, 10:20 AM
Lothar
Lothar - avatar
+ 2
Not without using slices or regex.or do double replace method in print call with count param.
16th Sep 2020, 11:05 AM
HBhZ_C
HBhZ_C - avatar
+ 1
abhay ur code out put is let chill out & chill tonight but i need output as let go out & chill tonight
16th Sep 2020, 10:40 AM
Kesava N
Kesava N - avatar
+ 1
You can using simple replace method: msg = msg.replace("go","chill",2))#output let chill out & chill tonight print(msg.replace("chill","go",1))#let go out & chill tonight Use regex if you would quik result. using regex: import re s = "let go out and go tongight" print(re.sub('go(?=\st)',"chill",s))
16th Sep 2020, 10:50 AM
HBhZ_C
HBhZ_C - avatar
+ 1
a="let go out and go tonight" b=a count=0 import re while True: replaceWith=len(b[:b.index("go")+len("go")])*" " b=b.replace(b[:b.index("go")+len("go")],replaceWith) count+=1 if count==1: b=b.replace("go","chill") index=b.index(re.search("\w",b).group()) print(a[:index]+b[index:]) break This does the work ,but I really wish there was a inbuilt function to do this !
16th Sep 2020, 12:03 PM
Abhay
Abhay - avatar
0
HBhZ output is fine but using another variable to store and again replace is not what i want. can we do it with the any default function using only once
16th Sep 2020, 10:54 AM
Kesava N
Kesava N - avatar
0
HBhZ , using slices we cannot do& i need to chk with regexp.
16th Sep 2020, 11:10 AM
Kesava N
Kesava N - avatar