Joining multiple strings if they are not empty in Python

Question:

I have four strings and any of them can be empty. I need to join them into one string with spaces between them. If I use:

new_string = string1 + ' ' + string2 + ' ' + string3 + ' ' + string4

The result is a blank space on the beginning of the new string if string1 is empty. Also, I have three blank spaces if string2 and string3 are empty.

How can I easily join them without blank spaces when I don’t need them?

Asked By: Goran

||

Answers:

>>> strings = ['foo','','bar','moo']
>>> ' '.join(filter(None, strings))
'foo bar moo'

By using None in the filter() call, it removes all falsy elements.

Answered By: ThiefMaster
strings = ['foo','','bar','moo']
' '.join([x for x in strings if x is not ''])
'foo bar moo'
Answered By: Greg Brown

If you KNOW that the strings have no leading/trailing whitespace:

>>> strings = ['foo','','bar','moo']
>>> ' '.join(x for x in strings if x)
'foo bar moo'

otherwise:

>>> strings = ['foo ','',' bar', ' ', 'moo']
>>> ' '.join(x.strip() for x in strings if x.strip())
'foo bar moo'

and if any of the strings have non-leading/trailing whitespace, you may need to work harder still. Please clarify what it is that you actually have.

Answered By: John Machin
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.