Andrew De Forest
Andrew De Forest

Reputation: 7338

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!

Upvotes: 2

Views: 8075

Answers (2)

ecatmur
ecatmur

Reputation: 157314

| 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"):

Upvotes: 7

ThiefMaster
ThiefMaster

Reputation: 318478

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.

Upvotes: 5

Related Questions