517643 观看

15回复

8223 作者的声誉

### 回应 15

841

98145 作者的声誉

``````myList = ['a','b','c','d']
myString = ",".join(myList )
``````

``````myString = ','.join(map(str, myList))
``````

67

7956 作者的声誉

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

>>>print ",".join(['a'])
a
``````

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

Edit2：感谢您的建议。将来，我将使用生成器而不是列表推导。

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

11

45509 作者的声誉

``````",".join(l)
``````

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

1

942 作者的声誉

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

（编辑：正如jmanning2k指出的那样，

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

4

38044 作者的声誉

``````from itertools import imap
l = [1, "foo", 4 ,"bar"]
",".join(imap(str, l))
``````

11

85318 作者的声誉

``````>>> l = [1, "foo", 4 ,"bar"]
>>> ",".join(str(bit) for bit in l)
'1,foo,4,bar'
``````

3

0 作者的声誉

``````l=['a', 1, 'b', 2]

print str(l)[1:-1]

Output: "'a', 1, 'b', 2"
``````

14

290141 作者的声誉

``````>>> alist = ['a', 1, (2, 'b')]
``````
• 标准方式

``````>>> ", ".join(map(str, alist))
"a, 1, (2, 'b')"
``````
• 替代解决方案

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

3

47 作者的声誉

``````string  =  ''.join([str(i) for i in list])
``````

15

16672 作者的声誉

`",".join(l)`不适用于所有情况。我建议将CSV模块与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'
``````

1

0 作者的声誉

``````>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [i[0] for i in myList]))
>>> print "Output:", myList
Output: Apple,Orange
``````

``````>>> myList = [['Apple'],['Orange']]
>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList]))
>>> print "Output:", myList
Output: Apple,Orange
``````

``````myList = ['Apple','Orange']
myList = ','.join(map(str, myList))
print "Output:", myList
Output: Apple,Orange
``````

5

1281 作者的声誉

``````>>> my_list = ['A', '', '', 'D', 'E',]
>>> ",".join([str(i) for i in my_list if i])
'A,D,E'
``````

`my_list`可以包含任何类型的变量。这样可以避免结果`'A,,,D,E'`

-2

188 作者的声誉

``````>>> 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'
``````

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

-1

1 作者的声誉

``````String = "Once:Upon:a:Time:A:Long:Time:Ago"
ding = String.split(':')

ring = (" , ").join(ding)

print(ring)
``````

1

1280 作者的声誉

``````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.
``````