1

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
ShayThan
  • 21
  • 2
  • The question is fine, how to replace the second accurance of a substring. – Hagai Wild Mar 29 '20 at 18:12
  • Answers that you have shared is slightly different in such a way that it is only replacing a single word which also have only one occurrence in a string. – ShayThan Mar 29 '20 at 18:13
  • 1
    I don't if there's a cleaner way of doing it, but here's: `index = text.find('cats', text.find('cats') + 1)` `a = text[:index] + 'dogs' + text[index + 4:] # 4 is 'dogs' length` – Hagai Wild Mar 29 '20 at 18:24
  • 1
    BTW, there are many ways to implement this. I think my suggetion isn't worth using, you can also do it with split and join. – Hagai Wild Mar 29 '20 at 18:30
  • 1
    Use this for the nth occurrence `text.replace('cats', '%s') % (('cats',) * (n - 1) + ('dogs',))` – Hagai Wild Mar 29 '20 at 18:40
  • What could be the general format let's say if we are having a function which have to replace either 2nd count or any nth count. What could be the possibilities? – ShayThan Mar 29 '20 at 19:30
  • @HagaiWild, I've tried by using split and join and yes it worked. – ShayThan Mar 30 '20 at 06:59

3 Answers3

0
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"))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Mr Bhati
  • 641
  • 7
  • 7
0

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
Vijay
  • 65
  • 10
0

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.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • P.p.s. Sorry ShayThan, I meant to answer way back but I guess I forgot, or saw the comments and thought Hagai Wild was going to write one. – wjandrea Apr 26 '20 at 23:27