Join list of items with different types to String in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Photo from Unsplash

Join list of items with different types to String in Python #

To join a list of items with different types to a string:

  1. Use the map() function to convert each item to a string.
  2. Call the join() method on a string separator.
  3. Pass the map object to the join() method.
main.py
my_list = ['a', 'b', 'c', 1, 2, 3] my_str = ', '.join(map(str, my_list)) print(my_str) # 👉️ 'a, b, c, 1, 2, 3'

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.

This is why we used the map() function to convert each item to a string.

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

An alternative approach is to pass a generator expression to the join() method.

main.py
my_list = ['a', 'b', 'c', 1, 2, 3] my_str = '-'.join(str(item) for item in my_list) print(my_str) # 👉️ 'a-b-c-1-2-3'

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

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

If you need to separate the list items with a space, call the join method on a string that contains a space.

main.py
my_list = ['a', 'b', 'c', 1, 2, 3] my_str = ' '.join(str(item) for item in my_list) print(my_str) # 👉️ 'a b c 1 2 3'

Similarly, you can use a newline (\n) to join the list items with a newline character.

main.py
my_list = ['a', 'b', 'c', 1, 2, 3] my_str = '\n'.join(str(item) for item in my_list) # a # b # c # 1 # 2 # 3 print(my_str)

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

main.py
my_list = ['a', 'b', 'c', 1, 2, 3] my_str = ''.join(str(item) for item in my_list) print(my_str) # 👉️ abc123
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.