为什么python设计为str(无)返回’None’而不是空字符串?
发布时间:2021-02-20 06:45:02 所属栏目:Python 来源:互联网
导读:在一些其他语言中,我知道,空字符串转换的直观结果应该是一个空字符串. 为什么 Python被设计为使“无”是一种特殊的字符串? 这可以在从函数检查返回值时导致额外的工作 result = foo() # foo will return None if failure if result is not None and len(str(
在一些其他语言中,我知道,空字符串转换的直观结果应该是一个空字符串.
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正在尝试冗长,使日志文件更容易理解? 解决方法通过检查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 无和’强制布尔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? (编辑:阜阳站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |