views:

37

answers:

1

I'm coming from a javascript backend to Python and I'm running into a basic but confusing problem

I have a string that can contain a value of either 'left', 'center', or 'right'. I'm trying to test if the variable contains either 'left' or 'right'.

In js its easy:

if( str === 'left' || str === 'right' ){}

However, in python I get a syntax error with this:

if str == 'left' || str == 'right':

Why doesn't this work, and what's the right syntax?

+6  A: 

Python's logical OR operator is called or. There is no ||.

if string == 'left' or string == 'right':
##                  ^^

BTW, in Python this kind of test is usually written as:

if string in ('left', 'right'):

## in Python ≥3.1, also possible with set literal
## if string in {'left', 'right'}:

Also note that str is a built-in function in Python. You should avoid naming a variable that clashes with them.

KennyTM
What is the difference between || and or in Python?
Geuis
Yes, logical or is `or`. The bitwise or is still `|` (unlike e.g. in Pascal (dialects?), which is rather weird). Edit @ Geius: There is no `||` in Python. That's why you get a syntax error and not unexpected behaviour.
delnan
| is a bitwise "or" operator in Python. However, it doesn't make sense when two of them are together, as in "||". Hence, the syntax error.
Matt Caldwell