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答案
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 |
是的,
当你implicitly
如果你想知道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></
零for example of any type的值,
任何空序列,for example,
任何for example,
用户定义的类的情况下),或在
在其他的事情考虑的对象的值是true of many types -我知道你是真实的。P></
操作和建立在布尔函数总是返回result that have a
用途:只
1 2 | if not your_variable: print("your_variable is empty") |
用途:为你的
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></