如何解决在印刷声明中,我在句子中提到了两只“猫”如何获得此功能来替换第二个“猫”?
def replace_ending(sentence,old,new):
if old in sentence:
i = sentence.index(old)
new_sentence = sentence[:i] + new
return new_sentence
return sentence
#print(replace_ending("It's raining cats and cats","cats","dogs"))
解决方法
您只需要使用rindex
而不是index
来获取最后一次出现的索引:
def replace_ending(sentence,old,new):
if old in sentence:
i = sentence.rindex(old) # this is the only difference
new_sentence = sentence[:i] + new
return new_sentence
return sentence
print(replace_ending("It's raining cats and cats","cats","dogs"))
输出:
正在下雨的猫和狗
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。