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

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

    If you want to do the shortcut way :) :

    ','.join([str(word) for word in wordList])
    

    But if you want to show off with logic :) :

    wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']
    stringText = ''
    
    for word in wordList:
        stringText += word + ','
    
    stringText = stringText[:-2]   # get rid of last comma
    print(stringText)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 16:23
    l=['a', 1, 'b', 2]
    
    print str(l)[1:-1]
    
    Output: "'a', 1, 'b', 2"
    
    0 讨论(0)
  • 2020-11-22 16:24

    ",".join(l) will not work for all cases. I'd suggest using the csv module with StringIO

    import StringIO
    import csv
    
    l = ['list','of','["""crazy"quotes"and\'',123,'other things']
    
    line = StringIO.StringIO()
    writer = csv.writer(line)
    writer.writerow(l)
    csvcontent = line.getvalue()
    # 'list,of,"[""""""crazy""quotes""and\'",123,other things\r\n'
    
    0 讨论(0)
  • 2020-11-22 16:24

    Here is a alternative solution in Python 3.0 which allows non-string list items:

    >>> alist = ['a', 1, (2, 'b')]
    
    • a standard way

      >>> ", ".join(map(str, alist))
      "a, 1, (2, 'b')"
      
    • the alternative solution

      >>> import io
      >>> s = io.StringIO()
      >>> print(*alist, file=s, sep=', ', end='')
      >>> s.getvalue()
      "a, 1, (2, 'b')"
      

    NOTE: The space after comma is intentional.

    0 讨论(0)
  • 2020-11-22 16:30
    >>> my_list = ['A', '', '', 'D', 'E',]
    >>> ",".join([str(i) for i in my_list if i])
    'A,D,E'
    

    my_list may contain any type of variables. This avoid the result 'A,,,D,E'.

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