如何在python中检查多个字符串是否为空

don*_*yor 0 python

我有投入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个输入为空,我想要.

我怎样才能以更高效,更优雅的方式做到这一点?

ale*_*cxe 5

您可以使用join()连接非空字符串(一行):

>>> s1 = 'test'
>>> s2 = ''
>>> s3 = ''
>>> ' '.join(s for s in (s1,s2,s3) if s)
'test'
Run Code Online (Sandbox Code Playgroud)

  • +1.虽然如果你使用`join`中的列表理解为[根据这个问题](http://stackoverflow.com/questions/9060653/list-comprehension-without-python)会更快 (3认同)