我想知道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)
Run Code Online (Sandbox Code Playgroud)
kit*_*tte 22
另请参阅此前一个推荐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
Run Code Online (Sandbox Code Playgroud)
值得注意的是,它不能用于"0"作为字符串,因为字符串确实包含某些内容 - 包含"0"的字符.为此你必须将它转换为int:
>>> a = "0"
>>> not a
False
>>> a = '0'
>>> not int(a)
True
Run Code Online (Sandbox Code Playgroud)
agf*_*agf 19
是的,bool.这是不完全一样- '0'是True的,但None,False,[],0,0.0,和""都是False.
bool在类似if或while语句,条件表达式或使用布尔运算符的条件中计算对象时隐式使用.
如果你想像PHP一样处理包含数字的字符串,你可以这样做:
def empty(value):
try:
value = float(value)
except ValueError:
pass
return bool(value)
Run Code Online (Sandbox Code Playgroud)
只需使用not:
if not your_variable:
print("your_variable is empty")
Run Code Online (Sandbox Code Playgroud)
和供您0 as string使用:
if your_variable == "0":
print("your_variable is 0 (string)")
Run Code Online (Sandbox Code Playgroud)
结合起来:
if not your_variable or your_variable == "0":
print("your_variable is empty")
Run Code Online (Sandbox Code Playgroud)
Python是关于简单性的,所以这个答案是:)
| 归档时间: |
|
| 查看次数: |
92081 次 |
| 最近记录: |