[] is None False >{} is None False-6ren">
gpt4 book ai didi

python - Python 的问题是没有测试?

转载 作者:太空宇宙 更新时间:2023-11-04 06:57:33 25 4
gpt4 key购买 nike

我喜欢对空变量使用 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,去编辑一些代码...

最佳答案

测试 x is None 测试 x 是否真的 None 对象(也就是说,如果name x 引用对象 None)。您要找的是truth value testing :

if "":
print "non-empty"
else:
print "empty"

if 将条件隐式转换为 bool。您也可以明确地这样做:

>>> bool("")
False
>>> bool("x")
True

关于python - Python 的问题是没有测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6497166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com