+ 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")
7 Answers
+ 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))
+ 2
Not without using slices or regex.or do double replace method in print call with count param.
+ 1
abhay ur code out put is
let chill out & chill tonight
but i need output as
let go out & chill tonight
+ 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))
+ 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 !
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
0
HBhZ , using slices we cannot do& i need to chk with regexp.