first_and_last函数通过使用message[0]或message[-1]访问字符,如果字符串的第一个字母与字符串的最后一个字母相同则返回True,如果它们不同则返回False。当检查空字符串的条件时,我得到这个错误:
Error on line 2:
if message[0] == message[1] :
IndexError: string index out of range
我不明白为什么我得到这个错误。下面是我的代码:
def first_and_last(message):
if message[0] == message[-1] or len(message) == 0:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
or
停止对第一个真操作数求值。因此,您必须首先检查消息长度,以避免对空字符串的索引访问:
def first_and_last(message):
if len(message) == 0 or message[0] == message[-1]:
return True
return False
或短:
def first_and_last(message):
return not message or message[0] == message[-1]