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

How to check if a variable is empty in python?

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

1
2
3
4
5
6
7
"" (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)


see also this which recommends the previous答案not关键字P></

how to check if a list is empty Python?P></

它只是generalizes to超过列表:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 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

notably will not work for恩,因为"0"as a字符串字符串does the事实contain something -含字符"0"。for你have to convert it to an int:P></

1
2
3
4
5
6
7
>>> a ="0"
>>> not a
False

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


是的,bool。这是not the same -确切的说因为是True'0'is,but NoneFalse[]0,,,,0.0""False,是的。P></

当你implicitly boolis used condition评价对象在安安whilestatement类ifor expression,条件,或与布尔算子。P></

如果你想知道PHP字符串处理含as something like does,你可以给你:P></

1
2
3
4
5
6
def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)


see section 5.1:P></

docs.python.org http:/ / /图书馆/ stdtypes.htmlP></

任何对象的真值测试can be for if,for或while使用安布尔condition or as below of the操作操作数。下面的值是错误的事情考虑:P></

NoneP></

FalseP></

零for example of any type的值,00L0.0,,,,0j。P></

任何空序列,for example,''()[]。P></

任何for example,{}空映射。P></

用户定义的类的情况下),或在__nonzero__()if the class defines __len__()method that when the method,返回布尔值False整数或零。[ 1 ]P></

在其他的事情考虑的对象的值是true of many types -我知道你是真实的。P></

操作和建立在布尔函数总是返回result that have a 0or for False虚假和1Truefor True or otherwise,除非stated。(例外:the important or总是返回布尔操作和操作数andone of their。)P></


用途:只notP></

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

用途:为你的0 as string布尔P></

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

组合它们:P></

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

Python简单is this is about),我知道答案:P></