Python中if not 判断为空
- if not x
not x 意为取反,在python中,None,False,空字典,空字符串,空列表和0都相当于False,取反则意为True
not None == not False == not '' == not 0 == not [] == not {} == not ()
当对象清晰为空时才能使用if not x
在一些特别的情况下需要注意
>>> x = []
>>> y = None
>>>
>>> x is None
False
>>> y is None
True
>>>
>>> not x is None
True
>>> not y is None
False
>>>
如果使用if not x这种写法的pythoner,必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()才行。
对于if x is not None和if not x is None写法,前者更清晰
而后者有可能使误解为if (not x) is None
因此推荐前者
if x is not None
浙公网安备 33010602011771号