You have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
Answer from unbeknown on Stack OverflowYou have to convert the ints to strings and then you can join them:
','.join([str(i) for i in list_of_ints])
You can use map to transform a list, then join them up.
",".join( map( str, list_of_things ) )
BTW, this works for any objects (not just longs).
How do I use the .join function on integers?
python - Creating comma-separated string from list - Stack Overflow
Convert a comma separated property to a List
Using C, convert a dynamic int array to a comma-separated string as cleanly as possible
I have a function that can add commas between lists and print them out as strings
def commaCode(listValue):
listValue.insert(-1, 'and')
NewlistValue = ', '.join(listValue)
print(NewlistValue)Here's the output:
cat, bat, and, sat
But I need this to work for integers as well. (and combinations of strings and integers).
How do I use the .join function on integers?
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'
>>>
If you are dealing with a csv file that is something other than the trivial example here, please do remember you are better off using the csv module to read and write csv, since CSV can be surprisingly complex.
Here is a write example:
import csv
x = [['Header\n1', 'H 2', 'H 3', 'H, 4'],[1,2,3,4],[5,6,7,8],[9,10,11,12]]
with open('/tmp/test.csv', 'w') as fout:
writer=csv.writer(fout)
for l in x:
writer.writerow(l)
Note the embedded comma in 'H, 4' and the embedded new line in 'Header\n1' that may trip up efforts to decode if not properly encoded.
The file 'test.csv' that the csv module produces:
"Header
1",H 2,H 3,"H, 4"
1,2,3,4
5,6,7,8
9,10,11,12
Note the quoting around "Header\n1" and "H, 4"` in the file so that the csv is correctly decoded in the future.
Now check you can read that back:
with open('/tmp/test.csv') as f:
csv_in=[[int(e) if e.isdigit() else e for e in row]
for row in csv.reader(f)]
>>> csv_in==x
True
Just sayin' You are usually better off using the tools in the library for csv.