您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:22:26 python 字数 2493 阅读 518 来源 www.jb51.cc/python

在一些其他语言中,我知道,空字符串转换的直观结果应该是一个空字符串. 为什么 Python被设计为使“无”是一种特殊的字符串? 这可以在从函数检查返回值时导致额外的工作 result = foo() # foo will return None if failure if result is not None and len(str(result)) > 0: # ... deal wi

概述

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正在尝试冗长,使日志文件更容易理解?

result = foo() # foo will return None if failure 
if result:
    # deal with result.
    pass

无和’强制布尔False.

如果你真的问为什么str(None)不返回“None”,那么我认为是因为它是必要的three-valued logic. 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(无)给你”请阅读另一个问题:Python: most idiomatic way to convert None to empty string?

总结

以上是编程之家为你收集整理的为什么python设计为str(无)返回’None’而不是空字符串?全部内容,希望文章能够帮你解决为什么python设计为str(无)返回’None’而不是空字符串?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶