Dr.*_*ogy 2 python string boolean
我偶然发现了这个,我找不到足够的答案:
x = ""
Run Code Online (Sandbox Code Playgroud)
那么为什么是:
x == True
False
x == False
False
x != True
True
x != False
True
Run Code Online (Sandbox Code Playgroud)
我是否应该得出结论x
既不是也不True
是False
?
检查 x 是否为 True 或 False:
bool("")
> False
bool("x")
> True
Run Code Online (Sandbox Code Playgroud)
有关is
和 的语义的详细信息==
,请参阅此问题
我是否应该断定x既不是真也不是假?
那就对了.x
既不True
是False
,也不是""
.差异从类型开始:
>>> print(type(""), type("x"), type(True), type(False))
builtins.str, builtins.str, builtins.bool, builtins.bool
Run Code Online (Sandbox Code Playgroud)
Python是一种高度面向对象的语言.因此,字符串是对象.与Python的好处是,他们可以有一个布尔值表示的if x: print("yes")
,如.对于字符串,这种表示是len(x)!=0
.