Convert a list of characters into a string

If I have a list of chars:

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

How do I convert it into a single string?

a = 'abcd'

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

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

This works in JavaScript or 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'

But in Python the join method is on the str class:

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

It is a little weird, isn't it? 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.


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

链接地址: http://www.djcxy.com/p/5442.html

上一篇: 如何将列表转换为字符串

下一篇: 将字符列表转换为字符串