Geu*_*uis 2 python if-statement
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' ){}
Run Code Online (Sandbox Code Playgroud)
However, in python I get a syntax error with this:
if str == 'left' || str == 'right':
Run Code Online (Sandbox Code Playgroud)
Why doesn't this work, and what's the right syntax?
ken*_*ytm 12
调用Python的逻辑OR运算符or.没有||.
if string == 'left' or string == 'right':
## ^^
Run Code Online (Sandbox Code Playgroud)
顺便说一句,在Python中,这种测试通常写成:
if string in ('left', 'right'):
## in Python ?3.1, also possible with set literal
## if string in {'left', 'right'}:
Run Code Online (Sandbox Code Playgroud)
另请注意,这str是 Python中的内置函数.您应该避免命名与它们冲突的变量.
| 归档时间: |
|
| 查看次数: |
10644 次 |
| 最近记录: |