I want to replace the second occurrence of "cats" in "It's raining cats and cats" with "dogs".
text = "Its raining cats and cats"
a = text.replace(str(text.endswith("cats")), "dogs")
print(a)
I want to replace the second occurrence of "cats" in "It's raining cats and cats" with "dogs".
text = "Its raining cats and cats"
a = text.replace(str(text.endswith("cats")), "dogs")
print(a)
def replace_ending(sentence, old, new):
sentence_array = sentence.split()
if sentence_array[-1]== old:
sentence = sentence.rsplit(" ",1)[0];
new_sentence = sentence + " " + new
return new_sentence
return sentence
print(replace_ending("It's raining cats and cats", "cats", "dogs"))
Try this:
text = "Its raining cats and cats".split(' ') # splits it at space
text[text.index('cats', text.index('cats')+1)] = 'dogs' # find where cat occurs after the first occurrence (if you have 3 instead of two and want to replace the third, this won't work) and replaces it
text = " ".join(text) # rejoins text using space
Start by finding the first occurrence, then replace after that point. Also set a count for str.replace
, to ensure that only the second occurrence is replaced.
text = "It's raining cats and cats"
old, new = 'cats', 'dogs'
offset = text.index(old) + 1
a = text[:offset] + text[offset:].replace(old, new, 1)
print(a) # -> "It's raining cats and dogs"
P.s. I also turned this into a super versatile library function which I'll probably publish on GitHub later. Follow this answer for an update, I guess.