你如何检查python中的变量是否相等

时间:2015-02-11 21:06:36

标签: python

我有一个行数组,位置5的值可以是以下值之一:

"Tablespace Free Space (MB)", "Tablespace Space Used (%)"

如果line[5]是其中任何一项,我需要做一些额外的工作。

我试过这个:

if (line[5] in ("Tablespace Space Used (%)")|("Tablespace Free Space (MB)"))

    # some other code here

我一直收到这个错误:

    if (line[5] in ("Tablespace Space Used (%)"|"Tablespace Free Space (MB)"))
                                                                             ^
SyntaxError: invalid syntax

2 个答案:

答案 0 :(得分:3)

您在:声明的末尾错过了if

但是,您的测试也使用了无效的语法;它会导致运行时错误(TypeError: unsupported operand type(s) for |: 'str' and 'str')。您想要创建一个元组或一组要测试的字符串,而不是使用|

if line[5] in ("Tablespace Space Used (%)", "Tablespace Free Space (MB)"):

if line[5] in {"Tablespace Space Used (%)", "Tablespace Free Space (MB)"}:

后者在技术上更有效率,除非您使用的是Python 2,其中集合未被优化为常量,就像元组版本中的元组一样。使用{...}创建集需要Python 2.7或更高版本。

答案 1 :(得分:1)

您使用==检查相等性

4 == 2*2
True

要使用if语句,请使用':'

结束该行
if line[5] in {'Tablespace Space Used (%)', 'Tablespace Free Space (MB)'}:
   do x
相关问题