Creating comma-separated string from list

27,791

Solution 1

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.

Solution 2

Just modify the argument to join so that each element is converted to a string:

x = [3, 1, 4, 1, 5]
y = ",".join(str(i) for i in x)
Share:
27,791
Karnivaurus
Author by

Karnivaurus

Updated on September 10, 2020

Comments

  • Karnivaurus
    Karnivaurus over 3 years

    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.

  • ueg1990
    ueg1990 almost 10 years
    thnx Austin...still getting used to helping out at Stackoverflow