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

后端 未结 14 1267
北海茫月
北海茫月 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:38

    Unless I'm missing something, ','.join(foo) should do what you're asking for.

    >>> ','.join([''])
    ''
    >>> ','.join(['s'])
    's'
    >>> ','.join(['a','b','c'])
    'a,b,c'
    

    (edit: and as jmanning2k points out,

    ','.join([str(x) for x in foo])
    

    is safer and quite Pythonic, though the resulting string will be difficult to parse if the elements can contain commas -- at that point, you need the full power of the csv module, as Douglas points out in his answer.)

提交回复
热议问题