将字符列表转换为字符串
如果我有一个字符列表:
a = ['a','b','c','d']
我如何将它转换为单个字符串?
a = 'abcd'
使用空字符串的join方法将所有字符串与中间的空字符串连接在一起,如下所示:
>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'
这适用于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不像JavaScript或其他流行的脚本语言那样是list对象中的一种方法? 这是Python社区如何思考的一个例子。 由于join返回一个字符串,它应该放在字符串类中,而不是列表类中,所以str.join(list)方法意味着:使用str作为分隔符将列表连接到一个新字符串中(在这种情况下, str是一个空字符串)。
不知何故,过了一段时间,我开始喜欢这种思维方式。 我可以抱怨Python设计中的很多事情,但不是关于它的一致性。
如果你的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' 。
