replace_ending 函数用新字符串替换句子中的旧字符串,但前提是句子以旧字符串结尾

Nit*_*hin 1 string python-3.x ends-with

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

print(replace_ending("It's raining cats and cats", "cats", "dogs")) 
# Should display "It's raining cats and dogs"
print(replace_ending("She sells seashells by the seashore", "seashells", 
"donuts")) 
# Should display "She sells seashells by the seashore"
print(replace_ending("The weather is nice in May", "may", "april")) 
# Should display "The weather is nice in May"
print(replace_ending("The weather is nice in May", "May", "April")) 
# Should display "The weather is nice in April"
Run Code Online (Sandbox Code Playgroud)

Nit*_*hin 5

答案如下。问题属于谷歌学习python。

def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence 
    if sentence.endswith(old):
    # 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 = sentence.rfind(old)
        new_sentence = sentence[:i]+new
    return new_sentence

# Return the original sentence if there is no match 
return sentence
Run Code Online (Sandbox Code Playgroud)