Join multiple Strings with possibly None values in Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Join multiple Strings with possibly None values in Python #

To join multiple strings with possibly None values:

  1. Use the join() method with an optional delimiter.
  2. Use the filter() function to filter out any None values.
  3. The join() method returns a string which is the concatenation of the strings in the iterable.
main.py
str_1 = 'Alice' str_2 = None str_3 = 'Carl' result = ', '.join(filter(None, [str_1, str_2, str_3])) print(result) # 👉️ "Alice, Carl"

We passed a comma as a delimiter but you can adjust it depending on your use case.

Here is an example that uses a space as a delimiter.

main.py
str_1 = 'Alice' str_2 = None str_3 = 'Carl' result = ' '.join(filter(None, [str_1, str_2, str_3])) print(result) # 👉️ "Alice Carl"

If you don't need a delimiter between the strings, call the join() method on an empty string.

main.py
str_1 = 'Alice' str_2 = None str_3 = 'Carl' result = ''.join(filter(None, [str_1, str_2, str_3])) print(result) # 👉️ "AliceCarl"

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

Note that the method raises a TypeError if there are any non-string values in the iterable.

The string the method is called on is used as the separator between elements.

main.py
my_list = ['a', 'b', 'c'] my_str = '-'.join(my_list) print(my_str) # 👉️ "a-b-c"

We used the filter() function to filter out any None values from the list.

main.py
str_1 = 'Alice' str_2 = None str_3 = 'Carl' result = ', '.join(filter(None, [str_1, str_2, str_3])) print(result) # 👉️ "Alice, Carl"

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

If you pass None for the function argument, all falsy elements of the iterable are removed.

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.