开发者

Check if string contains one value or another, syntax error?

开发者 https://www.devze.com 2023-01-23 06:33 出处:网络
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

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 wo开发者_如何学编程rk, and what's the right syntax?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消