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

后端 未结 14 1024
北海茫月
北海茫月 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)
    
    0 讨论(0)
  • 2020-11-22 16:36
    my_list = ['a', 'b', 'c', 'd']
    my_string = ','.join(my_list)
    
    'a,b,c,d'
    

    This won't work if the list contains integers


    And if the list contains non-string types (such as integers, floats, bools, None) then do:

    my_string = ','.join(map(str, my_list)) 
    
    0 讨论(0)
  • 2020-11-22 16:37

    Don't you just want:

    ",".join(l)
    

    Obviously it gets more complicated if you need to quote/escape commas etc in the values. In that case I would suggest looking at the csv module in the standard library:

    https://docs.python.org/library/csv.html

    0 讨论(0)
  • 2020-11-22 16:37

    My two cents. I like simpler an one-line code in python:

    >>> from itertools import imap, ifilter
    >>> l = ['a', '', 'b', 1, None]
    >>> ','.join(imap(str, ifilter(lambda x: x, l)))
    a,b,1
    >>> m = ['a', '', None]
    >>> ','.join(imap(str, ifilter(lambda x: x, m)))
    'a'
    

    It's pythonic, works for strings, numbers, None and empty string. It's short and satisfies the requirements. If the list is not going to contain numbers, we can use this simpler variation:

    >>> ','.join(ifilter(lambda x: x, l))
    

    Also this solution doesn't create a new list, but uses an iterator, like @Peter Hoffmann pointed (thanks).

    0 讨论(0)
  • 2020-11-22 16:38

    @jmanning2k using a list comprehension has the downside of creating a new temporary list. The better solution would be using itertools.imap which returns an iterator

    from itertools import imap
    l = [1, "foo", 4 ,"bar"]
    ",".join(imap(str, l))
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
提交回复
热议问题