2013-05-14 35 views
1

作爲後續這個原題: Python: Stripping elements of a string array based on first character of each element(有多個條件)指定的值有條件

我想知道如果我能擴大這個if語句:

with open(bom_filename, 'r') as my_file: 
    file_array = [word.strip() for word in my_file if word.startswith("/")] 

包括和第二條件:

with open(bom_filename, 'r') as my_file: 
    file_array = [word.strip() for word in my_file if (word.startswith("/")) & not(word.endswith("/"))] 

這會產生一個語法錯誤,但我希望有一些替代語法我可以使用!

+1

您是否記住''word.strip()'將在測試後執行**,以便''/ abc「不能通過? – eumiro 2013-05-14 13:39:52

回答

1
with open(bom_filename, 'r') as my_file: 
    file_array = [word.strip() for word in my_file if (word.startswith("/") and not(word.strip().endswith("/")))] 

您需要更改

if (word.startswith("/")) & not(word.endswith("/")) 

if (word.startswith("/") and not(word.strip().endswith("/"))) 

或有額外的括號去掉:(按@ viraptor的建議)

if word.startswith("/") and not word.strip().endswith("/") 

注意if(...)...必須包含所有邏輯,而不僅僅是if(word.startswith("/"))。並替換&這是一個按位運算符and

+0

字符串的末尾在條件檢查中沒有被剝離,所以你需要做一些事情,比如word.strip()。endswith(「/」),或者如果你剛剛剝掉了一個endline,word.endswith ( 「/ \ n」)。查看* re *模塊以使用正則表達式對字符串執行更復雜的模式匹配,例如re.match(「^ \ /.* \/$」,word.strip()) – mtadd 2013-05-14 13:44:14

+2

大多數括號也不需要。它可以只是'...如果word.starswith(「/」)而不是word.endswith(「/」)' – viraptor 2013-05-14 13:44:30

+0

@mtadd好點,更新以反映OP希望檢查「/」以排除任何可能「\ n」 – HennyH 2013-05-14 13:46:23