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"
发布于 2020-04-11 15:06:31
答案如下。这个问题属于谷歌对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
发布于 2020-05-07 20:14:40
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 = len(old)
new_sentence = sentence[:-i]+new
return new_sentence
# Return the original sentence if there is no match
return sentence
发布于 2020-06-05 16:17:39
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=len(sentence)
l=len(old)
new_sentence = sentence[0:i-l] + new
return new_sentence
# Return the original sentence if there is no match
return sentence
https://stackoverflow.com/questions/61158739
复制相似问题