Comparing the first and last character of a string in python

3.8k Views Asked by At

first_and_last function returns True if the first letter of the string is the same as the last letter of the string, False if they’re different, by accessing characters using message[0] or message[-1]. While checking the condition for an empty string I get tihis error:

Error on line 2:
    if message[0] == message[1] :
IndexError: string index out of range

I dont understand why am I getting this error. Here's my code below:

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

There are 1 best solutions below

0
user2390182 On BEST ANSWER

or stops evaluating operands on the first truthy operand. Hence, you must check the message length first in order to avoid the indexed access into the empty string:

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

Or shorter:

def first_and_last(message):
    return not message or message[0] == message[-1]