为什么设计为str(None)的python返回“None”而不是空字符串?

2024-05-23 20:16:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在我知道的其他一些语言中,空到字符串转换的直观结果应该是空字符串。 为什么Python被设计成“None”是某种特殊的字符串? 在检查函数的返回值时,这会导致额外的工作

result = foo() # foo will return None if failure 
if result is not None and len(str(result)) > 0:
    # ... deal with result 
    pass 

如果str(None)返回空字符串,则代码可能更短:

if len(str(result)) > 0:
    # ... deal with result 
    pass 

看起来Python试图变得冗长,使日志文件更容易理解?


Tags: 函数字符串none语言leniffoowith
2条回答

通过检查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',那么我相信这是因为three-valued logic必须返回。TrueFalseNone可以一起用于确定逻辑表达式是TrueFalse还是不能确定。标识函数是最容易表示的。

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'

现在,如果你真的想得到一个权威的答案,就去问圭多。


如果你真的想让str(None)给你''请阅读另一个问题:Python: most idiomatic way to convert None to empty string?

基本上,因为空字符串不是None的表示。None是与空字符串或任何其他内容不同的特殊值。如the docs所述,str应该

Return a string containing a nicely printable representation of an object.

基本上,str应该返回可打印和可读的内容。空字符串不是None的可读表示形式。

相关问题 更多 >