Оператор проекта:
Функция 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"