空字符串布尔逻辑

时间:2016-03-15 13:57:01

标签: python string boolean

我偶然发现了这一点,我无法找到足够的答案:

x = ""

为什么会这样:

x == True
False

x == False
False

x != True
True

x != False
True

我是否应该断定x既不是True也不是False

4 个答案:

答案 0 :(得分:5)

  

我是否应该断定x既不是真也不是假?

没错。 x既不是True也不是False,而是""。差异从类型开始:

>>> print(type(""), type("x"), type(True), type(False))
builtins.str, builtins.str, builtins.bool, builtins.bool

Python是一种高度面向对象的语言。因此,字符串是对象。 python的优点是它们可以为if x: print("yes")提供布尔表示,e。 g ..对于字符串,此表示为len(x)!=0

答案 1 :(得分:1)

检查x是否为真假:

bool("")
> False

bool("x")
> True

有关is==语义的详细信息,请参阅this question

答案 2 :(得分:1)

在python' =='测试平等。空字符串不等于True,因此比较结果为False。

您可以确定'真实性'将空字符串传递给bool函数:

>>> x = ''
>>> bool(x)
False

答案 3 :(得分:1)

在布尔上下文中,null / empty字符串为false(Falsy)。如果你使用

testString = ""

if not testString:
    print("NULL String")
else:
    print(testString)

正如snakecharmerb所说,如果你将字符串传递给bool()函数,它将返回True或False

>>> testString = ""
>>> bool(testString)
    False

>>> testString = "Not an empty string"
>>> bool(testString)
    True

请参阅此真值测试文档以了解有关此内容的更多信息:

Python 2:

https://docs.python.org/2/library/stdtypes.html#truth-value-testing

Python 3:

https://docs.python.org/3/library/stdtypes.html#truth-value-testing