简体   繁体   中英

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

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] .

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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