gpt4 book ai didi

string - Python:将 None 转换为空字符串的最惯用方法?

转载 作者:IT老高 更新时间:2023-10-28 12:30:59 29 4
gpt4 key购买 nike

执行以下操作最惯用的方法是什么?

def xstr(s):
if s is None:
return ''
else:
return s

s = xstr(a) + xstr(b)

更新:我正在采纳 Trypich 的使用 str(s) 的建议,这使得该例程适用于字符串以外的其他类型。我对 Vinay Sajip 的 lambda 建议印象深刻,但我想让我的代码相对简单。

def xstr(s):
if s is None:
return ''
else:
return str(s)

最佳答案

可能最短的是str(s or '')

因为 None 为 False,如果 x 为 false,“x or y”返回 y。见 Boolean Operators详细说明。它很短,但不是很明确。

关于string - Python:将 None 转换为空字符串的最惯用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1034573/

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