我想用“狗”代替“正在下雨的猫和猫”中第二次出现的“猫”。
text = "Its raining cats and cats"
a = text.replace(str(text.endswith("cats")), "dogs")
print(a)
答案 0 :(得分: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"))
答案 1 :(得分:0)
尝试一下:
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
答案 2 :(得分:0)
从查找第一次出现的位置开始,然后在该位置之后进行替换。还要为str.replace
设置一个 count ,以确保仅第二次出现被替换。
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。我还把它变成了一个超级通用的库函数,稍后我可能会在GitHub上发布它。我想请按照这个答案进行更新。