繁体   English   中英

运行以下代码时收到 python 语法错误

[英]Received a python syntax error while running the below code

抛出错误以验证字符串中的字符是否为空:

Python代码

def first_and_last(message):
  if(message[0] ==  message[-1] or len(message[0])==0):
     return True
   return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))

错误

Traceback (most recent call last):                                                                                            
  File "main.py", line 8, in <module>                                                                                         
    print(first_and_last(""))                                                                                                 
  File "main.py", line 2, in first_and_last                                                                                   
    if(message[0] ==  message[-1] or len(message[0])==0):                                                                     
IndexError: **string index out of range**

在访问其元素之前,您需要比较空字符串。 你的情况应该是:

if(len(message)==0 or message[0] ==  message[-1]):

它应该是len(message)而不是len(message[0])因为如果您的message为空,则不会有任何message[0]

您首先需要确保消息不是空字符串。 使用此方法,当第一个和最后一个字符相同时,它返回 0,它的值为 false 和 true。

def first_and_last(message):
  return len(message) and message[0] == message[-1]

尝试这个 :

def first_and_last(message):
  if(len(message)==0):
     return True
  elif(message[0] ==  message[-1] or len(message[0])==0):
     return True  
  return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))

错误是您还必须提及检查空字符串的情况,因为您在函数中传递了空字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM