This tutorial will discuss about unique ways to convert a list to a comma-separated string in Python.
Table Of Contents
Convert list of strings to comma-separated string
If you know that your list has only strings, then this method is for you. Call the join()
function on a string object, containing a comma
. Pass the list of strings to the join()
function. It will merge all the strings in the given list by using a comma
as a separator, and returns a big comma separated string
.
Let’s see the complete example,
listOfStrs = ['11', '12', '13', '14', '15', '16', '17'] # Convert a list to a comma separated string strValue = ','.join(listOfStrs) print(strValue)
Output
11,12,13,14,15,16,17
It converted a list of strings to a comma-separated string.
But this example will only work if list has string elements only. Whereas, if string has any element which is of not string type, then this code will give error. Look at the next example for the solution.
Frequently Asked:
Convert list with some non string elements to comma-separated string
If list has some elements which are not of string type, then first we need to convert those elements to string type. Then only we can pass list items to the join()
function.
Call the map()
function, and pass str()
and the given list as arguments in it. It will convert the type of all the elements in list to string. Then, call the join()
function with a string containing comma
, and pass those converted strings elements to it.
Let’s see the complete example,
listOfNumbers = [11, 12, 13, 14, 15, 16, 17] strValue = ','.join(map(str, listOfNumbers)) print(strValue)
Output
11,12,13,14,15,16,17
We converted a list to a list of integers in Python.
Summary
We learned about two different ways to convert a list to a list of integers in Python. Thanks.