Join multiple Strings with possibly None values in Python

avatar
Borislav Hadzhiev

Last updated: Feb 18, 2023
5 min

banner

# Table of Contents

  1. Join multiple Strings with possibly None values in Python
  2. Join multiple strings if they aren't empty in Python

# 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 = 'Bobby' str_2 = None str_3 = 'Hadz' result = ', '.join(filter(None, [str_1, str_2, str_3])) print(result) # ๐Ÿ‘‰๏ธ "Bobby, Hadz"

join multiple strings with possibly none values

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 = 'Bobby' str_2 = None str_3 = 'Hadz' result = ' '.join(filter(None, [str_1, str_2, str_3])) print(result) # ๐Ÿ‘‰๏ธ "Bobby Hadz"

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

main.py
str_1 = 'Bobby' str_2 = None str_3 = 'Hadz' result = ''.join(filter(None, [str_1, str_2, str_3])) print(result) # ๐Ÿ‘‰๏ธ "BobbyHadz"

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

# Handling not-string values in the list

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

If some of the values you are joining are not of type string, use the map() function to convert them.

main.py
str_1 = 'Bobby' str_2 = None str_3 = 'Hadz' str_4 = 500 result = ', '.join( filter( None, map(str, [str_1, str_2, str_3, str_4]) ) ) print(result) # ๐Ÿ‘‰๏ธ "Bobby, None, Hadz, 500"

handling not string values in the list

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The map() function gets called with each element in the list and passes each value to the str() class.

The string the join() 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 = 'Bobby' str_2 = None str_3 = 'Hadz' result = ', '.join(filter(None, [str_1, str_2, str_3])) print(result) # ๐Ÿ‘‰๏ธ "Bobby, Hadz"

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).

# Using a generator expression instead of filter()

You can also use a generator expression instead of the filter() function.

main.py
str_1 = 'Bobby' str_2 = None str_3 = 'Hadz' result = ' '.join( value for value in [str_1, str_2, str_3] if value is not None ) print(result) # ๐Ÿ‘‰๏ธ Bobby Hadz

using generator expression instead of filter

We used a generator expression to iterate over the list of values.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current value is not None and return the result.

The str.join() method only gets called with not-None values, so the code sample achieves the same result as using the filter() function.

# Join multiple strings if they aren't empty in Python

If you need to join multiple strings if they aren't empty:

  1. Use the filter() function to filter out all falsy values.
  2. Call the join() method on a string separator.
  3. Pass the filter object to the join() method.
main.py
my_strings = ['apple', '', 'banana', '', 'kiwi', ''] result = ' '.join(filter(None, my_strings)) print(result) # ๐Ÿ‘‰๏ธ 'apple banana kiwi'

join multiple strings if they are not empty

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.

main.py
my_strings = ['apple', '', 'banana', '', 'kiwi', '', None, 0] # ๐Ÿ‘‡๏ธ ['apple', 'banana', 'kiwi'] print(list(filter(None, my_strings)))

Notice that all of the falsy values from the list are filtered out in the result.

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).

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.

# Handling not-string values in the list

If your list contains numbers or other types, convert all of the values to string before calling join().

main.py
my_strings = ['apple', 1, 'banana', 2, 'kiwi', '', None, 0] result = ' '.join(map(str, filter(None, my_strings))) print(result) # ๐Ÿ‘‰๏ธ 'apple 1 banana 2 kiwi'

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

main.py
my_strings = ['apple', '', 'banana', '', 'kiwi', ''] result = '-'.join(filter(None, my_strings)) print(result) # ๐Ÿ‘‰๏ธ 'apple-banana-kiwi'

If you don't need a separator and just want to join the iterable's elements into a string, call the join() method on an empty string.

main.py
my_strings = ['a', '', 'b', '', 'c', ''] result = ''.join(filter(None, my_strings)) print(result) # ๐Ÿ‘‰๏ธ 'abc'

# Join multiple strings if they aren't empty using a generator expression

An alternative approach to join strings only if they aren't empty is to use a generator expression.

main.py
my_strings = ['apple', '', 'banana', '', ' ', 'kiwi', ''] result = ' '.join(item for item in my_strings if item.strip()) print(result) # ๐Ÿ‘‰๏ธ 'apple banana kiwi'

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

We used it to make sure there aren't any strings that only contain spaces in the result.

We passed a generator expression to the str.join() method.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev