我有投入s1,s2,s3.我只有在它们确实存在时才需要连接它们.
我做了:
s1 = s1.strip()
s2 = s2.strip()
s3 = s3.strip()
if s1 and s2 and s3:
input = s1 + ' ' + s2 + ' ' + s3
if s1 and s2:
input = s1 + ' ' + s2
if s1 and s3:
input = s1 + ' ' + s3
if s2 and s3:
input = s2 + ' ' + s3
....
...
Run Code Online (Sandbox Code Playgroud)
我不想要test ( white space ).test如果其余2个输入为空,我想要.
我怎样才能以更高效,更优雅的方式做到这一点?
您可以使用join()连接非空字符串(一行):
>>> s1 = 'test'
>>> s2 = ''
>>> s3 = ''
>>> ' '.join(s for s in (s1,s2,s3) if s)
'test'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |