Return empty string as True in given string
You wrote that you want to compare the first character to the last, so you have to use
[-1]
and not[3]
. Otherwise you are comparing the first and the fourth characters.You can use
if not message
to check if it's an empty stringSince you are returning, you don't need to check if they do not match.
def first_and_last(message):
if not message:
return True
return message[0] == message[-1]
As noted in the comments this can be pushed a bit more into a single line:
def first_and_last(message):
return not message or message[0] == message[-1]
You can use if not
def first_and_last(message):
if not message:
return False
else: return True
print(first_and_last("else")) #True
print(first_and_last("tree")) #True
print(first_and_last("")) #False