【发布时间】:2021-01-03 19:12:16
【问题描述】:
def replace_ending(sentence, old, new):
# Check if the old string is at the end of the sentence
# if old in sentence:
# i = len(sentence)
# N = len(old)
# wrong_sentence = sentence[0:i-N] + new
# return wrong_sentence
if old in sentence == True:
i = len(sentence)
N = len(old)
correct_sentence = sentence[0:i-N] + new
return correct_sentence
return sentence
print(replace_ending("She sells seashells by the seashore", "seashells", "donuts"))
# # Should display "She sells seashells by the seashore"
结果顶部:She sells seashells by thedonuts
结果底部:She sells seashells by the seashore
我一直试图弄清楚为什么两个“if 语句”都会产生“True”作为输出。但是,打印结果不同。有谁知道这是什么原因?
【问题讨论】:
-
试试
if sentence.endswith(old): -
抱歉,我弄糊涂了。比尔是对的,当被问及“如果句子中的旧 == True”即“False”时,底部的陈述结果为 false。因此,它只返回句子。
标签: python