如何在python中检查变量是否为空?

时间:2012-05-11 04:18:15

标签: python

我想知道python是否有任何函数,如php空函数(http://php.net/manual/en/function.empty.php),它使用以下条件检查变量是否为空

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)

4 个答案:

答案 0 :(得分:21)

另请参阅上一个推荐not关键字

的答案

How to check if a list is empty in Python?

它概括为不仅仅是列表:

>>> a = ""
>>> not a
True

>>> a = []
>>> not a
True

>>> a = 0
>>> not a
True

>>> a = 0.0
>>> not a
True

>>> a = numpy.array([])
>>> not a
True

值得注意的是,它不能作为字符串用于“0”,因为字符串确实包含某些内容 - 包含“0”的字符。为此,你必须将它转换为int:

>>> a = "0"
>>> not a
False

>>> a = '0'
>>> not int(a)
True

答案 1 :(得分:19)

是的,bool。它不完全相同 - '0'True,但NoneFalse[]00.0,并且""都是False

当您在boolif语句,条件表达式或布尔运算符等条件下计算对象时,会隐式使用

while

如果你想像PHP那样处理包含数字的字符串,你可以这样做:

def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

答案 2 :(得分:4)

见5.1节:

http://docs.python.org/library/stdtypes.html

可以测试任何对象的真值,用于if或while条件或下面布尔运算的操作数。以下值被视为false:

None

False

任何数字类型的零,例如00L0.00j

任何空序列,例如''()[]

任何空映射,例如{}

用户定义类的实例,如果类定义了__nonzero__()__len__()方法,则该方法返回整数零或bool值False。 [1]

所有其他值都被认为是真的 - 因此许多类型的对象始终为真。

具有布尔结果的操作和内置函数始终返回0False表示false,1True表示true,除非另有说明。 (重要的例外:布尔运算orand总是返回其中一个操作数。)

答案 3 :(得分:3)

只需使用not

if not your_variable:
    print("your_variable is empty")

以及0 as string使用:

if your_variable == "0":
    print("your_variable is 0 (string)")

将它们结合起来:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python是关于简单性的,所以这个答案是:)