Joining multiple strings if they are not empty in Python
Solution 1:
>>> strings = ['foo','','bar','moo']
>>> ' '.join(filter(None, strings))
'foo bar moo'
By using None
in the filter()
call, it removes all falsy elements.
Solution 2:
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.