简体   繁体   中英

How can I replace the second occurrence in a string?

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"

Ps 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM