Makes a mistake of out of range because the last string is empty, that is, its size is zero. So, it has no index (no index message[0]
, nor message[-1]
, or any other value), and any attempt to obtain any character from it will give error.
To solve, you can test whether the string is empty and return True
, otherwise return the result of the comparison:
def first_and_last(message):
if not message: # string vazia, retorna True
return True
return message[0] == message[-1]
print(first_and_last("else")) # True
print(first_and_last("tree")) # False
print(first_and_last("")) # True
The if not message
test if the string is empty. This is possible because an empty string is considered a false value.
Then, if the string is not empty, return the result of comparing the first to the last character. Note that you do not need the if
here, for the result of the comparison message[0] == message[-1]
is already a boolean and you can return it directly.
In general, any expression in this way:
if condição:
return True
return False
May be replaced by:
return condição
That’s why instead of:
if(message[0] == message[-1]):
return True
return False
I simply did:
return message[0] == message[-1]
Finally, it is possible to simplify the two conditions so:
def first_and_last(message):
return not message or message[0] == message[-1]
That is, returns the result of not message or message[0] == message[-1]
(string is empty, or the first and last characters are equal).
This case does not give error because the operator or
is a short-Circuit Operator: If the first condition is true, it does not even check the second. Then first I check if the string is empty. If it is not, then the second condition is checked. But if the string is empty, the expression already returns True
, not at the risk of giving the error of out of Bounds.
Thank you very much! !
– Daniel McCarthy
@Danielmccarthy If the answer solved your problem, you can accept it, see here how and why to do it. It is not mandatory, but it is a good practice of the site, to indicate to future visitors that it solved the problem. And when I get 15 points, you can also vote in all the answers you found useful.
– hkotsubo