user1094705
user1094705

Reputation: 5

Unsupported operand type(s) for 'str' and 'str'. Python

I've got the IF statement;

if contactstring == "['Practice Address Not Available']" | contactstring == "['']":

I'm not sure what is going wrong(possibly the " ' "s?) but I keep getting the error mentioned in the title.

I've looked in other questions for answers but all of them seem to be about using mathematical operates on strings which is not the case here. I know this question is kind of lazy but I've been coding all day and I'm exhausted, I just want to get this over with quickly.(Python newb)

Upvotes: 0

Views: 7528

Answers (3)

kindall
kindall

Reputation: 184191

The problem here is the bitwise-or operator |. In a Boolean context that would normally work OK, but | has higher precedence than == so Python is trying to evaluate "['Practice Address Not Available']" | contactstring first. Both of those operands are strings, and you can't bitwise-or two strings. Using the more correct or avoids this problem since it's lower precedence than ==.

Upvotes: 2

lvc
lvc

Reputation: 35069

| is a bitwise or operator in Python, and has precedence so that Python parses this as:

if contactstring == (""['Practice Address Not Available']"" | contactstring) == "['']":

Which generates the error you see.

It seems what you want is a logical or operator, which is spelled 'or' in Python:

if contactstring == ""['Practice Address Not Available']"" or contactstring == "['']":

Will do what you expect. However, since you're comparing the same variable against a range of values, this is even better:

 if contactstring in ("['Practice Address Not Available']", ['']):

Upvotes: 13

user166390
user166390

Reputation:

The | is a bitwise operator which doesn't work on strings...

Using or (a boolean logic operator) will yield better results.

Upvotes: 4

Related Questions