如果我有一个字符列表:

a = ['a','b','c','d']

如何将其转换为单个字符串?

a = 'abcd'

当前回答

这可能是最快的方法:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'

其他回答

你也可以像这样使用operator.concat():

>>> from operator import concat
>>> a = ['a', 'b', 'c', 'd']
>>> reduce(concat, a)
'abcd'

如果你使用的是python3,你需要前置:

>>> from functools import reduce

因为内置的reduce()已经从Python 3中移除,现在存在于functools.reduce()中。

reduce函数也可以工作

import operator
h=['a','b','c','d']
reduce(operator.add, h)
'abcd'

使用空字符串的join方法将所有字符串和中间的空字符串连接在一起,如下所示:

>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'

如果你的Python解释器是旧的(例如1.5.2,这在一些旧的Linux发行版上很常见),你可能没有join()作为任何旧字符串对象的方法,你将需要使用string模块。例子:

a = ['a', 'b', 'c', 'd']

try:
    b = ''.join(a)

except AttributeError:
    import string
    b = string.join(a, '')

字符串b将是'abcd'。

h = ['a','b','c','d','e','f']
g = ''
for f in h:
    g = g + f

>>> g
'abcdef'