作者ggirls (哥)
看板Python
標題[問題] `in None` 的 exception 怎麼避免?
時間Mon Aug 20 12:21:42 2018
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://webptt.com/m.aspx?n=bbs/Python/M.1534738905.A.9C0.html
1F:推 TitanEric: if e is None就可以 08/20 12:24
※ 編輯: ggirls (114.136.239.216), 08/20/2018 12:28:20
2F:推 Yshuan: 別用!e 假如是0,False,[],() 這些會混淆 08/20 13:06
3F:→ Yshuan: 從'a' in e來看, 期許字串可用 isinstance(e, basestring) 08/20 13:09
4F:→ s860134: if e and 'a' in e: 08/20 13:11
5F:→ s860134: 因為原本條件就已經限制 e 中包含 'a',故前面只要確定 e 08/20 13:12
6F:→ s860134: 不是 None 就好了,當然這寫法在特殊情形下是錯的 08/20 13:12
7F:推 handsomeLin: 請善用and 08/20 15:57