I am attempting to replace every other instance of the word "happy" in a file using python. Here is the input and expected output.
Input: "hello happy car happy dog happy lane happy"
Output: "hello happy car sad dog happy lane sad"
I am attempting to adjust the following code but having problems. Any suggestions are greatly appreciated.
def nth_repl_all(s, sub, repl, nth):
find = s.find(sub)
# loop util we find no match
i = 1
while find != -1:
# if i is equal to nth we found nth matches so replace
if i == nth:
s = s[:find]+repl+s[find + len(sub):]
i = 0
# find + len(sub) + 1 means we start after the last match
find = s.find(sub, find + len(sub) + 1)
i += 1
return s
sub,repl, andnth? I'm guessing thatsubis going to be replaced with"happy",nthwith2(so every second, or every other"happy"in strings) - but what isrepl?sub = "happy",repl = "sad", andnth = 2replis what OP wants to replacesubwith. Okay, that makes more sense.