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

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

提交回复
热议问题