Как я могу отладить мою Python реализацию replace_ending ()? - PullRequest
0 голосов
/ 17 апреля 2020

Оператор проекта:

Функция 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"

Ответы [ 2 ]

0 голосов
/ 17 апреля 2020

Вы должны использовать нарезку от конца строки "предложения", чтобы проверить последнюю подстроку, которая соответствует "старой" строке. Использование нарезки строк для заполнения пробелов в вопросе, который вы описали:

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

    # Return the original sentence if there is no match 
    return sentence
0 голосов
/ 17 апреля 2020

Попробуйте:

sentence = "She sells house shoes by my house"

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

print(replace_ending(sentence, 'house', 'sofa'))
print(replace_ending(sentence, 'wagon', 'sofa'))

возврат

'She sells house shoes by my sofa'
'She sells house shoes by my house'
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...