Python的问题是无测试?

时间:2011-06-27 18:19:15

标签: python

我喜欢使用 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来编辑一些代码...

5 个答案:

答案 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 NoneTrue

答案 3 :(得分:1)

NoneNone。我认为你要找的是空listdictstr

的布尔值

例如:

>>> 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'