How would you make a comma-separated string from a list of strings?

后端 未结 14 1244
北海茫月
北海茫月 2020-11-22 16:07

What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance

14条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 16:21

    I would say the csv library is the only sensible option here, as it was built to cope with all csv use cases such as commas in a string, etc.

    To output a list l to a .csv file:

    import csv
    with open('some.csv', 'w', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(l)  # this will output l as a single row.  
    

    It is also possible to use writer.writerows(iterable) to output multiple rows to csv.

    This example is compatible with Python 3, as the other answer here used StringIO which is Python 2.

提交回复
热议问题