【发布时间】:2021-01-02 14:53:25
【问题描述】:
这是问题:- 修改 first_and_last 函数,如果字符串的第一个字母与字符串的最后一个字母相同,则返回 True,如果它们不同,则返回 False。请记住,您可以使用 message[0] 或 message[-1] 访问字符。 小心你如何处理空字符串,它应该返回 True,因为没有什么等于没有。
当我这样写代码时:-
def first_and_last(message):
if len(message) == 0:
return True
elif message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# output:-
True
False
True
但是当我这样写代码时:-
def first_and_last(message):
if message[0] == message[-1]:
return True
elif len(message) == 0:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# output:-
True
False
Traceback (most recent call last):
File "C:/Users/Sidje/PycharmProjects/untitled2/SId.py", line 11, in <module>
print(first_and_last(""))
File "C:/Users/Sidje/PycharmProjects/untitled2/SId.py", line 2, in first_and_last
if message[0] == message[-1]:
IndexError: string index out of range
当我用 elif 编写 len 函数时,当语句为空时程序不工作,但它适用于其他条件。 这是为什么呢?
【问题讨论】:
-
这就是为什么它说
Be careful how you handle the empty string -
啊,现在明白了:)