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

问题描述 投票:-1回答:1

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"

经过20多次的努力,我无法解决此问题我在if函数中尝试过endswith(),但无法理解切片机制!帮帮我!

python replace format str-replace
1个回答
0
投票

您可以做这样的事情

def replace_ending(sentence, old, new):
    if sentence[len(sentence) - len(old):] == old:
        new_sentence = sentence[:len(sentence) - len(old)]
        new_sentence += new
        return new_sentence

    return sentence

输出:

It's raining cats and dogs
She sells seashells by the seashore
The weather is nice in May
The weather is nice in April
© www.soinside.com 2019 - 2024. All rights reserved.