Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison in python

I've been working my way through Python, but can't seem to get past string comparisons. I wrote a function that takes user input and evaluates it. User input can only be either "a" or "b", otherwise an error occurs. I have been using this:

def checkResponse(resp):
    #Make the incoming string trimmed & lowercase
    respRaw = resp.strip()
    respStr = respRaw.lower()
    #Make sure only a or b were chosen
    if respStr != "a" | respStr != "b":
        return False
    else:
        return True

However, when I input a or b, I receive this: TypeError: unsupported operand type(s) for |: 'str' and 'str'

Is this the incorrect way to compare a string? Is there a built in function to do this like with Java? Thanks!

like image 218
Andrew De Forest Avatar asked Mar 05 '26 14:03

Andrew De Forest


2 Answers

| is the bitwise or operator. You want or. (You actually want and.)

You wrote:

if respStr != "a" | respStr != "b":

Bitwise operators have high precedence (similar to other arithmetic operators), so this is equivalent to:

if respStr != ("a" | respStr) != "b":

where the two != operations are chained comparison operators (x != y != z is equivalent to x != y and y != z). It's meaningless to apply bitwise or to two strings.

You meant to write:

if respStr != "a" and respStr != "b":

You could also write, using chained operators:

if "a" != respStr != "b":

Or, using the containment operator in:

if respStr not in ("a", "b"):
like image 67
ecatmur Avatar answered Mar 07 '26 05:03

ecatmur


What you want is respStr != 'a' and respStr != 'b' (or is the boolean operator, | the bitwise one - however, you need and for your check).

However you can write the condition in an even nicer way without repeating the variable name:

return respStr in ('a', 'b')

This will return True if respStr is a or b and False otherwise.

like image 45
ThiefMaster Avatar answered Mar 07 '26 03:03

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!