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?

1 Answer 1

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'
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Though it's quicker if you use a list comprehension inside join as per this question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.