Reputation: 37846
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?
Upvotes: 0
Views: 173
Reputation: 473753
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'
Upvotes: 5