Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining multiple strings if they are not empty in Python

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?

like image 425
Goran Avatar asked Dec 24 '11 20:12

Goran


People also ask

How do you join two strings without space in Python?

First, we use the split() function to return a list of the words in the string, using sep as the delimiter Python string. Then, we use join() to concatenate the iterable.

How do you concatenate to an empty string in Python?

To append to an empty string in python we have to use “+” operator to append in a empty string.

How do you concatenate 3 strings in Python?

To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.


2 Answers

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

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

like image 90
ThiefMaster Avatar answered Oct 18 '22 21:10

ThiefMaster


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.

like image 31
John Machin Avatar answered Oct 18 '22 22:10

John Machin