Joining multiple strings if they are not empty in Python

Goran picture Goran · Dec 24, 2011 · Viewed 42.8k times · Source

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?

Answer

ThiefMaster picture ThiefMaster · Dec 24, 2011
>>> strings = ['foo','','bar','moo']
>>> ' '.join(filter(None, strings))
'foo bar moo'

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