将字符列表转换为字符串

问题:将字符列表转换为字符串

如果我有一个字符列表:

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

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

a = 'abcd'

If I have a list of chars:

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

How do I convert it into a single string?

a = 'abcd'

回答 0

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

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

Use the join method of the empty string to join all of the strings together with the empty string in between, like so:

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

回答 1

这可以在许多流行的语言(例如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'])

为什么对象中join的方法list不像JavaScript或其他流行的脚本语言那样?这是Python社区如何思考的一个示例。由于join返回的是字符串,因此应将其放置在字符串类中,而不是列表类中,因此该str.join(list)方法意味着:使用str分隔符将列表连接到新字符串中(本例中str为空字符串)。

过了一段时间,我莫名其妙地爱上了这种思维方式。我可以抱怨Python设计中的很多事情,但不能抱怨它的连贯性。

This works in many popular languages like JavaScript and Ruby, why not in Python?

>>> ['a', 'b', 'c'].join('')
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'

Strange enough, in Python the join method is on the str class:

# this is the Python way
"".join(['a','b','c','d'])

Why join is not a method in the list object like in JavaScript or other popular script languages? It is one example of how the Python community thinks. Since join is returning a string, it should be placed in the string class, not on the list class, so the str.join(list) method means: join the list into a new string using str as a separator (in this case str is an empty string).

Somehow I got to love this way of thinking after a while. I can complain about a lot of things in Python design, but not about its coherence.


回答 2

如果您的Python解释器较旧(例如,1.5.2在某些较旧的Linux发行版中很常见),则您可能无法join()在任何旧的字符串对象上将其用作方法,而需要使用字符串模块。例:

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

try:
    b = ''.join(a)

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

字符串b将为'abcd'

If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join() available as a method on any old string object, and you will instead need to use the string module. Example:

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

try:
    b = ''.join(a)

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

The string b will be 'abcd'.


回答 3

这可能是最快的方法:

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

This may be the fastest way:

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

回答 4

减少功能也起作用

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

The reduce function also works

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

回答 5

如果列表包含数字,则可以map()与结合使用join()

例如:

>>> arr = [3, 30, 34, 5, 9]
>>> ''.join(map(str, arr))
3303459

If the list contains numbers, you can use map() with join().

Eg:

>>> arr = [3, 30, 34, 5, 9]
>>> ''.join(map(str, arr))
3303459

回答 6

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

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

>>> g
'abcdef'

回答 7

除了str.join这是最自然的方式,一种可能性是使用io.StringIO和滥用一次writelines编写所有元素:

import io

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

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

印刷品:

abcd

当将此方法与生成器函数或不是a tuple或a 的可迭代器一起使用时list,它将保存临时创建的列表,该列表join确实可以一次性分配正确的大小(并且1个字符的字符串列表在内存方面非常昂贵) )。

如果您的内存不足,并且输入的对象是惰性求值,则此方法是最佳解决方案。

besides str.join which is the most natural way, a possibility is to use io.StringIO and abusing writelines to write all elements in one go:

import io

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

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

prints:

abcd

When using this approach with a generator function or an iterable which isn’t a tuple or a list, it saves the temporary list creation that join does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

If you’re low in memory and you have a lazily-evaluated object as input, this approach is the best solution.


回答 8

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

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

如果您使用的是Python 3,则需要先添加:

>>> from functools import reduce

由于内置函数reduce()已从Python 3中删除,现在位于中functools.reduce()

You could also use operator.concat() like this:

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

If you’re using Python 3 you need to prepend:

>>> from functools import reduce

since the builtin reduce() has been removed from Python 3 and now lives in functools.reduce().