通过检查来检查字符串中是否包含字符len(str(result))绝对不是pythonic(参见http://www.python.org/dev/peps/pep-0008/)。
result = foo() # foo will return None if failure
if result:
# deal with result.
pass
None并''强制转换为布尔值False。
如果你真的要问为什么str(None)会返回'None',那么我相信是因为它是三值逻辑所必需的。True,False并且None可以一起使用来确定一个逻辑表达式是True,False还是不能确定。恒等函数是最容易表示的。
True -> 'True'
False -> 'False'
None -> 'None'
str(None)如果是,以下内容将非常奇怪'':
>>> or_statement = lambda a, b: "%s or %s = %s" % (a, b, a or b)
>>> or_statement(True, False)
'True or False = True'
>>> or_statement(True, None)
'True or None = True'
>>> or_statement(None, None)
'None or None = None'
现在,如果您真的想要一个权威的答案,请询问 Guido。
如果你真的想str(None)给你,''请阅读另一个问题:Python: most idiommatic way to convert None to empty string?