0

I have inputs s1, s2, s3. I need to concatenate them only if they really exist.

I did:

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
....
...

e.g. I dont want test ( white space ). I want test if the rest 2 inputs are empty.

how can I do this in more efficient and elegant way?

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

5

You can use join() to join non-empty strings (one line):

>>> s1 = 'test'
>>> s2 = ''
>>> s3 = ''
>>> ' '.join(s for s in (s1,s2,s3) if s)
'test'
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 3
    +1. Though it's quicker if you use a list comprehension inside `join` as [per this question](http://stackoverflow.com/questions/9060653/list-comprehension-without-python) – Ffisegydd Apr 03 '14 at 15:46