【发布时间】:2020-07-10 02:51:37
【问题描述】:
我想将“It's raining cat and cats”中第二次出现的“cats”替换为“dogs”。
text = "Its raining cats and cats"
a = text.replace(str(text.endswith("cats")), "dogs")
print(a)
【问题讨论】:
-
问题很好,如何替换子串的第二个精度。
-
您共享的答案略有不同,它只替换了一个在字符串中也只出现一次的单词。
-
如果有更清洁的方法,我不会这样做,但这里是:
index = text.find('cats', text.find('cats') + 1)a = text[:index] + 'dogs' + text[index + 4:] # 4 is 'dogs' length -
顺便说一句,有很多方法可以实现这一点。我认为我的建议不值得使用,您也可以使用 split 和 join 来完成。
-
第n次使用这个
text.replace('cats', '%s') % (('cats',) * (n - 1) + ('dogs',))