我想知道Python是否有类似于PHP empty函数(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)
我想知道Python是否有类似于PHP empty函数(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)
可以参考之前的回答,建议使用not
关键字。
这适用于不仅仅是列表:
>>> 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"的字符。对于这种情况,您必须将其转换为整数:
>>> a = "0"
>>> not a
False
>>> a = '0'
>>> not int(a)
True
是的,bool
。它不是完全相同的--'0'
是True
,但None
,False
,[]
,0
,0.0
和""
都是False
。
在条件语句中(例如if
或while
语句,条件表达式或布尔运算符),当您评估对象时,将隐式使用bool
。
如果你想像PHP一样处理包含数字的字符串,你可以做这样的事情:
def empty(value):
try:
value = float(value)
except ValueError:
pass
return bool(value)
只需要使用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强调简洁,这个回答也是如此 :)
None
False
任何数字类型的零,例如,0
,0L
,0.0
,0j
。''
,()
,[]
。{}
。__nonzero__()
或__len__()
方法,并且该方法返回整数零或bool值False
,则用户定义类的实例也被视为假 [1]。0
或False
,并且true的1
或True
,除非另有说明。(重要例外:布尔运算or
和and
总是返回它们的操作数之一。)你可以使用 not 关键字。
if not a
print("a is empty")
not
不是一个命令,而是一个关键词。它也不是一个函数,所以你不需要(也不应该)使用括号。not
也会隐式地转换为布尔值然后取反;你并不总是想要取反来获取一个布尔值。 - agf