Convert list of integers to comma-separated string in Python

avatar

Borislav Hadzhiev

Last updated: Aug 31, 2022

banner

Photo from Unsplash

Convert list of integers to comma-separated string in Python #

To convert a list of integers to a comma-separated string:

  1. Use a generator expression to iterate over the list.
  2. Use the str() class to convert each integer to a string.
  3. Use the str.join() method to join the values into a string with a comma separator.
main.py
list_of_integers = [1, 3, 5, 7] my_str = ','.join(str(item) for item in list_of_integers) print(my_str) # 👉️ 1,3,5,7

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, you have to convert all of the values to strings before calling join().

We used a generator expression to iterate over the list and used the str() class to convert each integer to a string.

main.py
list_of_integers = [1, 3, 5, 7] my_str = ','.join(str(item) for item in list_of_integers) print(my_str) # 👉️ 1,3,5,7
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 the elements.

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

main.py
list_of_integers = [1, 3, 5, 7] my_str = ''.join(str(item) for item in list_of_integers) print(my_str) # 👉️ '1357'

If you need to convert the list of integers to a space-separated string, call the join() method on a string containing a space.

main.py
list_of_integers = [1, 3, 5, 7] my_str = ' '.join(str(item) for item in list_of_integers) print(my_str) # 👉️ 1 3 5 7

Alternatively, you can use the map() function to convert the values in the list to strings before calling join().

main.py
list_of_integers = [1, 3, 5, 7] my_str = ' '.join(map(str, list_of_integers)) print(my_str) # 👉️ 1 3 5 7

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

The str() class gets called with each number in the list and converts the values to strings.

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.