Sha*_*bus 19 python string string-concatenation
将"更好"理解为更快,更优雅,更易读.
我有两个字符串(a和b)可以为null或不.并且我希望只有当两者都不为空时才用连字符连接它们:
a - b
a (如果b为null)
b (其中a为null)
Hoo*_*ady 47
# Concatenates a and b with ' - ' or Coalesces them if one is None
'-'.join([x for x in (a,b) if x])
Run Code Online (Sandbox Code Playgroud)
编辑
以下是此算法的结果(请注意,None将与''的作用相同):
>>> '-'.join([x for x in ('foo','bar') if x])
'foo-bar'
>>> '-'.join([x for x in ('foo','') if x])
'foo'
>>> '-'.join([x for x in ('','bar') if x])
'bar'
>>> '-'.join([x for x in ('','') if x])
''
Run Code Online (Sandbox Code Playgroud)
*另请注意,在下面的帖子中,Rafael的评估仅在过滤方法的1000次迭代中显示出.0002秒的差异,可以推断出这样小的差异可能是由于当时可用系统资源的不一致运行脚本.我在几次迭代中运行了他的timeit实现,并发现任何一种算法在大约50%的时间内都会更快,也不会大幅度提高.因此显示它们基本相同.
tox*_*tes 35
简单的事情怎么样:
# if I always need a string even when `a` and `b` are both null,
# I would set `output` to a default beforehand.
# Or actually, as Supr points out, simply do `a or b or 'default'`
if a and b:
output = '%s - %s' % (a, b)
else:
output = a or b
Run Code Online (Sandbox Code Playgroud)
编辑:这个帖子中有很多有趣的解决方案.我选择这个解决方案是因为我强调可读性和快速性,至少在实现方面.它不是最具扩展性或最有趣的解决方案,但是对于这个范围它可以工作,并且让我能够非常快速地进入下一个问题.
ice*_*ime 31
哇,似乎是个热门话题:p我的建议:
' - '.join(filter(bool, (a, b)))
Run Code Online (Sandbox Code Playgroud)
这使:
>>> ' - '.join(filter(bool, ('', '')))
''
>>> ' - '.join(filter(bool, ('1', '')))
'1'
>>> ' - '.join(filter(bool, ('1', '2')))
'1 - 2'
>>> ' - '.join(filter(bool, ('', '2')))
'2'
Run Code Online (Sandbox Code Playgroud)
显然,None行为''与此代码相似.
zen*_*poy 12
这是一个选项:
("%s - %s" if (a and b) else "%s%s") % (a,b)
Run Code Online (Sandbox Code Playgroud)
编辑:正如mgilson指出的那样,这个代码会以None"更好的方式(但不太可读的方式)" 失败:
"%s - %s" % (a,b) if (a and b) else (a or b)
Run Code Online (Sandbox Code Playgroud)