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

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

    Why the map/lambda magic? Doesn't this work?

    >>> foo = ['a', 'b', 'c']
    >>> print(','.join(foo))
    a,b,c
    >>> print(','.join([]))
    
    >>> print(','.join(['a']))
    a
    

    In case if there are numbers in the list, you could use list comprehension:

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

    or a generator expression:

    >>> ','.join(str(x) for x in foo)
    

提交回复
热议问题