如果我有一个字符列表:
a = ['a','b','c','d']
如何将它转换为单个字符串?
a = 'abcd'
使用空字符串的 join
方法将所有字符串用空字符串连接起来,如下所示:
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'
' '.join(list)
将列表中的元素用空格拼接起来。其中引号内的空格表示要在每个元素之间插入一个空格。 - clifgray"".join(['a','b','c'])
的意思是将数组中的所有元素连接起来,用空字符串作为分隔符。同样地," hi ".join(["jim", "bob", "joe"])
会创建一个字符串 "jim hi bob hi joe"
。 - Jacklynn这在许多流行的编程语言中有效,例如JavaScript和Ruby,为什么Python不行?
>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
很奇怪,在Python中join
方法是在str
类上定义的:
# this is the Python way
"".join(['a','b','c','d'])
为什么在Python的list对象中,像JavaScript或其他流行脚本语言一样,join不是一个方法?这是Python社区思维方式的一个例子。由于join返回一个字符串,应该将其放置在字符串类中,而不是列表类中,因此str.join(list)方法的含义是:使用str作为分隔符(在这种情况下,str是一个空字符串)将列表连接成一个新字符串。string.join()
和许多动态语言中大多数集合都有的join()
方法。关于可迭代对象,我想对于这些语言来说并不是问题,因为将可迭代对象封装在集合构造器中并在join()
方法中链接起来同样容易(且易读)。 - Paulo Scardinejoin()
,而需要使用字符串模块。例如:a = ['a', 'b', 'c', 'd']
try:
b = ''.join(a)
except AttributeError:
import string
b = string.join(a, '')
字符串b
将为'abcd'
。
这可能是最快的方法:
>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'
'' .join(['a','b','c'])
快大约20%。 - bigeagle''.join()
更易于阅读。 - Luiz Damimimport operator
h=['a','b','c','d']
reduce(operator.add, h)
'abcd'
(reduce + '' h)
或(apply + h)
都可以工作。但是在Python中,加法运算符只接受两个操作数,因此需要使用reduce。否则,您可以执行operator.add(*h)
,因为在Python中,apply
已被正式弃用,而推荐使用扩展调用语法(又称http://en.wikipedia.org/wiki/Variadic_function)。 - Brian Mintonmap()
与join()
一起使用。>>> arr = [3, 30, 34, 5, 9]
>>> ''.join(map(str, arr))
3303459
''.join([str(i) for i in arr])
更符合Pythonic的风格。 - user1767754h = ['a','b','c','d','e','f']
g = ''
for f in h:
g = g + f
>>> g
'abcdef'
''.join(h)
方法可以远远超过逐个添加的方法。 - Martijn Pietersstr.join
方法之外,另一种可能性是使用 io.StringIO
并滥用 writelines
一次性写入所有元素:import io
a = ['a','b','c','d']
out = io.StringIO()
out.writelines(a)
print(out.getvalue())
打印:
abcd
tuple
或list
的可迭代对象,则可以避免join
创建临时列表来一次性分配正确大小(由于内存方面,一个由1个字符字符串组成的列表非常昂贵)。operator.concat()
}}:>>> from operator import concat
>>> a = ['a', 'b', 'c', 'd']
>>> reduce(concat, a)
'abcd'
>>> from functools import reduce
由于Python 3中已经移除了内置的reduce()
函数,现在它被放在了functools.reduce()
中。