Karnivaurus Karnivaurus - 2 months ago 9
Python Question

Creating comma-separated string from list

I have a list of ints and want to create a comma-separated string. The following:

x = [3, 1, 4, 1, 5]
y = ",".join(x)


Give the error:

TypeError: sequence item 0: expected string, int found


How do I create the string? I could manually convert every element from int to string, insert this into a new list, and then do the join on this new list, but I'm wondering if there is a cleaner solution.

Answer

str.join only accepts an iterable of strings, not one of integers. From the docs:

str.join(iterable)

Return a string which is the concatenation of the strings in the iterable iterable.

Thus, you need to convert the items in x into strings. You can use either map or a list comprehension:

x = [3, 1, 4, 1, 5]
y = ",".join(map(str, x))

x = [3, 1, 4, 1, 5]
y = ",".join([str(item) for item in x])

See a demonstration below:

>>> x = [3, 1, 4, 1, 5]
>>>
>>> ",".join(map(str, x))
'3,1,4,1,5'
>>>
>>> ",".join([str(item) for item in x])
'3,1,4,1,5'
>>>
Comments