做以下事情最常用的方式是什么?
def xstr(s):
if s is None:
return ''
else:
return s
s = xstr(a) + xstr(b)
更新:我正在整合Tryptich的建议,使用str(s),这使得这个例程适用于除字符串之外的其他类型。Vinay Sajip的lambda建议给我留下了深刻的印象,但我想让我的代码相对简单。
def xstr(s):
if s is None:
return ''
else:
return str(s)
发布于 2009-06-23 19:28:18
如果您实际上希望函数的行为类似于str()
内置函数,但在参数为None时返回空字符串,请执行以下操作:
def xstr(s):
if s is None:
return ''
return str(s)
发布于 2012-08-31 20:28:41
可能最短的应该是str(s or '')
因为没有一个是假的,如果x是假的,"x或y“返回y。有关详细说明,请参阅Boolean Operators。它很简短,但不是很明确。
发布于 2009-06-23 19:21:12
def xstr(s):
return '' if s is None else str(s)
https://stackoverflow.com/questions/1034573
复制相似问题