我想知道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)
我想知道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)
另请参阅this previous answer推荐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”的字符。为此,您必须将其转换为 int:
>>> a = "0"
>>> not a
False
>>> a = '0'
>>> not int(a)
True
是的,bool
。它不完全一样—— '0'
is True
,但是None
, False
, []
, 0
, 0.0
, and ""
are all False
。
bool
if
当您在条件(如orwhile
语句、条件表达式或布尔运算符)中计算对象时,会隐式使用。
如果您想像 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是关于简单的,所以这个答案:)
见第 5.1 节:
http://docs.python.org/library/stdtypes.html
可以测试任何对象的真值,用于 if 或 while 条件或作为以下布尔运算的操作数。以下值被认为是错误的:
None
False
任何数字类型的零,例如 , 0
, 0L
, 。0.0
0j
任何空序列,例如''
, ()
, []
.
任何空映射,例如{}
.
用户定义类的实例,如果该类定义了一个__nonzero__()
or__len__()
方法,当该方法返回整数零或 bool 值时False
。[1]
所有其他值都被认为是真的——所以许多类型的对象总是真的。
除非另有说明,否则具有布尔结果的操作和内置函数始终返回0
或False
为假和1
或为真。True
(重要的例外:布尔运算总是返回它们or
的and
操作数之一。)
您可以使用not关键字。
if not a
print("a is empty")