Python 将字符列表转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4481724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:56:23  来源:igfitidea点击:

Convert a list of characters into a string

pythonstring

提问by nos

If I have a list of chars:

如果我有一个字符列表:

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

How do I convert it into a single string?

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

a = 'abcd'

采纳答案by Daniel Stutzbach

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

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

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

回答by Paulo Scardine

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

这适用于许多流行的语言,如 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'

Strange enough, in Python the joinmethod is on the strclass:

奇怪的是,在 Python 中,该join方法在str类上:

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

Why joinis not a method in the listobject 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 stras a separator (in this case stris an empty string).

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

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.

不知何故,我在一段时间后开始喜欢这种思维方式。我可以抱怨 Python 设计中的很多东西,但不能抱怨它的连贯性。

回答by bigeagle

This may be the fastest way:

这可能是最快的方法:

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

回答by Bill

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

>>> g
'abcdef'

回答by Kyle

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:

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

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

try:
    b = ''.join(a)

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

The string bwill be 'abcd'.

字符串b将为'abcd'.

回答by cce

The reduce function also works

减少功能也有效

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

回答by Tonechas

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

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

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

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

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

>>> from functools import reduce

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

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

回答by yask

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

如果列表包含数字,您可以使用map()with join()

Eg:

例如:

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

回答by Jean-Fran?ois Fabre

besides str.joinwhich is the most natural way, a possibility is to use io.StringIOand abusing writelinesto write all elements in one go:

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

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 tupleor a list, it saves the temporary list creation that joindoes to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

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

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

如果您的内存不足并且您有一个延迟评估的对象作为输入,则此方法是最佳解决方案。