Function that compares characters from a string and returns true or false

Asked

Viewed 272 times

3

I’m trying to make a function that should return true or false if the first and last characters are equal.

However, comparing them is giving error of out of range and I can’t identify the reason:

def first_and_last(message):
    if(message[0] == message[-1]):
       return True
    return False
print(first_and_last("else")) #should return True
print(first_and_last("tree")) #should return False
print(first_and_last("")) #should return True

2 answers

3


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

  • @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.

1

Another way to resolve this issue is:

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


palavra = input('Digite uma palavra: ')

print(f'\033[32m{first_and_last(palavra)}')

Note that when this code is executed we receive the following message: Digite uma palavra. At this point we must type the desired word and press ente.

At this time the word is captured as string and sent to the function first_and_last. Once there, your size is checked. If the string size is 0, that is, the string is empty, the return will be True. If the string is not empty, it will be checked whether the first and last letter of the string are equal. Positive case the function returns True and, if not, the function returns False.

Observing

When the string is empty, its size will be 0. This means to say that both the letter inicial as to the letter final are equal to vazio.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.