我喜欢使用 is None 测试空变量,它非常灵活,简单且实用。它现在似乎停止了工作:
>"" is None
False
>[] is None
False
>{} is None
False
发生了什么事?
我在Debian / Sid i686 GNU / Linux上使用Python 2.6.6(r266:84292,2010年12月27日,00:02:40)[GCC 4.4.5]。
编辑:来自Sven Marnach使用bool(“”)的精彩提示。 brb,off来编辑一些代码...
答案 0 :(得分:7)
测试x is None
测试x
确实是 None
对象(即,如果名称x
引用了对象{{ 1}})。您要找的是truth value testing:
None
if "":
print "non-empty"
else:
print "empty"
隐式将条件转换为if
。你也可以明确地这样做:
bool
答案 1 :(得分:2)
is
测试实例身份 - 即使{} is {}
也是假的。
>>> {} is {}
False
答案 2 :(得分:1)
它从未奏效。只有None is None
为True
。
答案 3 :(得分:1)
仅None
为None
。我认为你要找的是空list
,dict
和str
例如:
>>> if "":
... print 'woo'
... else:
... print 'hoo'
...
hoo
{}
和[]
答案 4 :(得分:0)
如果您只想检查空值,最好使用以下内容:
a = {}
b = []
c = ""
if a:
print 'non-empty dict'
else:
print 'empty dict'
if b:
print 'non-empty list'
else:
print 'empty list'
if c:
print 'non-empty string/value'
else:
print 'empty string/value'