2015-02-11 78 views
0

我有一個線陣,在位置值5可以是下列值:你如何檢查是否變量等於在python

"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 
+1

你缺少一個':'在結束你的線。 – merlin2011 2015-02-11 21:08:32

+1

您需要在if語句的末尾添加':'。例如:如果'(行[5]中( 「用於表空間的空間(%)」, 「表空間可用空間(MB)」):' – Andrew 2015-02-11 21:08:53

+0

此外,關係或蟒是 「或」,而不是管 – sharjeel 2015-02-11 21:19:30

回答

1

您使用==檢查平等

4 == 2*2 
True 

要使用if語句,總結了該行 ':'

if line[5] in {'Tablespace Space Used (%)', 'Tablespace Free Space (MB)'}: 
    do x 
+0

爲什麼你使用'in'仍然不是''==? – 2015-02-11 22:51:44

+0

沒有看到OP的聲明「,如果行[5]是任何這些我需要做一些額外的工作,「將修訂 – 2015-02-11 22:55:02

+0

當然,但爲什麼不使用會員的考驗還在 – 2015-02-11 23:00:16

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或更高版本。

+0

@martinPeiters。 ,我得到這個錯誤:如果線[5] { 「表空間已用空間(%)」, 「表空間可用空間(MB)」}: ^ 語法錯誤:無效的語法 – user1471980 2015-02-11 21:19:59

+0

@ user1471980:Python版本您使用的是?'{...}'爲集合需要Python 2.7或向上。 – 2015-02-11 21:22:44

相關問題