Python中空字符串、空字典、空列表、0、None的布尔值判断问题

>>> bool(0)
False
>>> bool("")
False
>>> bool([])
False
>>> bool({})
False
>>> bool(None)
False

-------------

>>> 0 == False
True
>>> “” == False
False
>>> [] == False
False
>>> {} == False
False
>>> None == False
False

-------------
PEP 8:

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

Yes: if not seq:
if seq:

No: if len(seq):
if not len(seq):
Python中空字符串、空字典、空列表、0、None的布尔值判断问题


1 回复

在Python里,这些值在布尔上下文的判断结果很直接,记住这个规律就行:

  • FalseNoneFalse、数值0(包括0.0)、空序列''[]())、空映射{})。
  • True:其他几乎所有值。

所以,你问的这些:

  • bool("") -> False
  • bool({}) -> False
  • bool([]) -> False
  • bool(0) -> False
  • bool(None) -> False

写条件判断时,利用这个特性可以让代码更简洁。比如检查列表my_list是否非空,直接写 if my_list: 就行,不用写 if len(my_list) > 0:

总结:空容器、零值和None在布尔判断中均为False。

回到顶部