Convert a list to a comma-separated string in Python

avatar

Borislav Hadzhiev

Last updated: Aug 31, 2022

banner

Photo from Unsplash

Convert a list to a comma-separated string in Python #

Use the str.join() method to convert a list to a comma-separated string, e.g. my_str = ','.join(my_list). The str.join() method will join the list's elements into a string with a comma separator.

main.py
# ✅ Convert list of strings to comma-separated string list_of_strings = ['one', 'two', 'three'] my_str = ','.join(list_of_strings) print(my_str) # 👉️ one,two,three # -------------------------------- # ✅ Convert list of integers to comma-separated string 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

We used the str.join() method to convert a list to a comma-separated string.

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 strings before calling join().

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

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

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.

main.py
list_of_strings = ['one', 'two', 'three'] my_str = ','.join(list_of_strings) print(my_str) # 👉️ one,two,three

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_strings = ['one', 'two', 'three'] my_str = ''.join(list_of_strings) print(my_str) # 👉️ onetwothree

If you need to join the list's elements with a space separator, call the join() method on a string containing a space.

main.py
list_of_strings = ['one', 'two', 'three'] my_str = ' '.join(list_of_strings) print(my_str) # 👉️ one two three

You can also use the map() function to convert the items 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.