简体   繁体   English

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

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

Errors is thrown to verify if the character in a string is empty:抛出错误以验证字符串中的字符是否为空:

Python 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(""))

Error错误

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**

You need to compare for an empty string before you access its elements.在访问其元素之前,您需要比较空字符串。 Your condition should be:你的情况应该是:

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

And it should be len(message) and not len(message[0]) because if your message is empty, there would not be any message[0] .它应该是len(message)而不是len(message[0])因为如果您的message为空,则不会有任何message[0]

You first need to make sure that the message is not empty string.您首先需要确保消息不是空字符串。 use this method, it returns 0 which evaluates false, and true when first and last chars are same.使用此方法,当第一个和最后一个字符相同时,它返回 0,它的值为 false 和 true。

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

try this :尝试这个 :

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(""))

The error was you have to mention the case of checking empty string as well since you were passing the empty string in the function.错误是您还必须提及检查空字符串的情况,因为您在函数中传递了空字符串。

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

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