看板 Python 關於我們 聯絡資訊
for e in es: if 'a' in e: print(e) 上面的程式,e 有可能是 None,所以 if 'a' in e: 會發生 Exception 一種是用 if !e: 先把這種情況濾掉;一種是抓這種 Exception 再處理。 請問還有別的比較簡潔的方法嗎? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.136.239.216 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1534738905.A.9C0.html
TitanEric: if e is None就可以 08/20 12:24
※ 編輯: ggirls (114.136.239.216), 08/20/2018 12:28:20
Yshuan: 別用!e 假如是0,False,[],() 這些會混淆 08/20 13:06
Yshuan: 從'a' in e來看, 期許字串可用 isinstance(e, basestring) 08/20 13:09
s860134: if e and 'a' in e: 08/20 13:11
s860134: 因為原本條件就已經限制 e 中包含 'a',故前面只要確定 e 08/20 13:12
s860134: 不是 None 就好了,當然這寫法在特殊情形下是錯的 08/20 13:12
handsomeLin: 請善用and 08/20 15:57