How to join a list of strings in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Photo from Unsplash

Join a list of strings in Python #

To join a list of strings in Python:

  1. Call the str.join() method on a string separator.
  2. Pass the list to the join() method.
  3. The result will be a string containing the list items separated by the provided separator.
main.py
my_list = ['a', 'b', 'c', 'd'] # 👇️ with space separator my_str = ' '.join(my_list) print(my_str) # 👉️ 'a b c d' # 👇️ without separator print(''.join(my_list)) # 👉️ 'abcd' # 👇️ with hyphen separator print('-'.join(my_list)) # 👉️ 'a-b-c-d'

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.

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

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

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

We used the function to convert each item in the list to a string, before passing the items to the str.join() method.

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'

If you need to join the list of strings with spaces, call the method on a string that contains a space.

main.py
my_list = ['a', 'b', 'c'] # 👇️ with space separator my_str = ' '.join(my_list) print(my_str) # 👉️ 'a b c'

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

main.py
my_list = ['a', 'b', 'c'] my_str = '\n'.join(my_list) # a # b # c print(my_str)

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_list = ['a', 'b', 'c', 'd'] # 👇️ with space separator my_str = ''.join(my_list) # a # b # c print(my_str) # 👉️ 'abcd'
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.