Mar*_*son 139 python string idioms
做以下事情的最惯用方法是什么?
def xstr(s):
if s is None:
return ''
else:
return s
s = xstr(a) + xstr(b)
Run Code Online (Sandbox Code Playgroud)
更新:我正在使用Tryptich的建议来使用str(s),这使得这个例程适用于除字符串之外的其他类型.Vinay Sajip的lambda建议给我留下了深刻的印象,但我想保持我的代码相对简单.
def xstr(s):
if s is None:
return ''
else:
return str(s)
Run Code Online (Sandbox Code Playgroud)
Sil*_*ost 137
def xstr(s):
return '' if s is None else str(s)
Run Code Online (Sandbox Code Playgroud)
Vin*_*jip 94
如果您知道该值将始终为字符串或None:
xstr = lambda s: s or ""
print xstr("a") + xstr("b") # -> 'ab'
print xstr("a") + xstr(None) # -> 'a'
print xstr(None) + xstr("b") # -> 'b'
print xstr(None) + xstr(None) # -> ''
Run Code Online (Sandbox Code Playgroud)
Tri*_*ych 87
如果您确实希望函数的行为与str()内置函数类似,但在参数为None时返回空字符串,请执行以下操作:
def xstr(s):
if s is None:
return ''
return str(s)
Run Code Online (Sandbox Code Playgroud)
dor*_*vak 87
可能是最短的
str(s or '')
因为None是False,如果x是false,"x或y"返回y.有关详细说明,请参阅布尔运算符.这很简短,但不是很明确.
Ale*_*lli 57
return s or '' 对你陈述的问题会很好!
Kry*_*ski 14
def xstr(s):
return s or ""
Run Code Online (Sandbox Code Playgroud)
def xstr(s):
return {None:''}.get(s, s)
Run Code Online (Sandbox Code Playgroud)
功能方式(单线)
xstr = lambda s: '' if s is None else s
Run Code Online (Sandbox Code Playgroud)
更新:
我现在主要用这个方法:
some_string = None
some_string or ''
Run Code Online (Sandbox Code Playgroud)
如果 some_string 不是NoneType,则将在or那里短路并返回它,否则返回空字符串。
老的:
Max 函数在 python 2.x 中有效,但在 3.x 中无效:
max(None, '') # Returns blank
max("Hello", '') # Returns Hello
Run Code Online (Sandbox Code Playgroud)
一个巧妙的单线代码可以在其他一些答案上进行构建:
s = (lambda v: v or '')(a) + (lambda v: v or '')(b)
Run Code Online (Sandbox Code Playgroud)
甚至只是:
s = (a or '') + (b or '')
Run Code Online (Sandbox Code Playgroud)