replace_ending 函数用新字符串替换句子中的旧字符串,但前提是句子以旧字符串结尾。如果句子中旧字符串出现多次,则只替换末尾的一个,而不是全部替换。例如,replace_ending("abcabc", "abc", "xyz") 应该返回 abcxyz,而不是 xyzxyz 或 xyzabc。字符串比较区分大小写,因此 replace_ending("abcabc", "ABC", "xyz") 应返回 abcabc(未进行任何更改)。
def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
if ___:
# Using i as the slicing index, combine the part
# of the sentence up to the matched string at the
# end with the new string
i = ___
new_sentence = ___
return new_sentence
# Return the original sentence if there is no match
return sentence …Run Code Online (Sandbox Code Playgroud)