Python: Comparing empty string to False is False, why?
如果
例如,与
1 2 3 4 | >>> 0 == False True >>> 0.0 == False True |
谢谢
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false:
False ,None , numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a__bool__() method.The operator
not yieldsTrue if its argument is false,False otherwise.https://docs.python.org/3/reference/expressions.html#comparisons
但是:
The operators
< ,> ,== ,>= ,<= , and!= compare the values of two objects. The objects do not need to have the same type....
Because all types are (direct or indirect) subtypes of
object , they inherit the default comparison behavior fromobject . Types can customize their comparison behavior by implementing rich comparison methods like__lt__() ...https://docs.python.org/3/reference/expressions.html#boolean-operations
因此,技术实现的答案是,它的行为方式是这样的,因为
对于
(*在任何合理构建的语言中)
这样的比较不是"Python式的"(也就是说,经验丰富的Python程序员自然不会这么做)。Pythonic方法是在一个布尔上下文中使用一个值,如
1 2 3 4 5 6 | if lst: print(headers) for item in lst: print(item.format()) else: print(no_data_message) |
而不是使用常见的、但不太像Python的
不幸的是,在某些方面,python的设计者认为
但仅仅因为一个
- 数值零点
None - 空字符串
- 空容器(列表、元组、dict)
他们不可能都平等!
如果您想查看官方解释,只需按如下方式进行赋值:
1 2 3 4 5 6 7 8 9 | print(bool(None) == False) print(False == False) print(bool(0) == False) print(bool(0.0) == False) print(bool(0j) == False) print(bool('') == False) print(bool(()) == False) print(bool([]) == False) print(bool({}) == False) |
因为
另一方面,