我有一堆字节字符串(str
,不是 unicode
,在 python 2.7 中)包含 unicode 数据(在 utf-8
编码中) .
我正在尝试加入它们(通过 "".join(utf8_strings)
或 u"".join(utf8_strings)
)抛出
UnicodeDecodeError: 'ascii' codec can't decode byte 0xec in position 0: ordinal not in range(128)`
有什么方法可以对非 ascii 字符串使用 .join()
方法吗?当然我可以将它们连接在一个 for 循环中,但这不符合成本效益。
最佳答案
使用 ''.join()
连接字节串效果很好;如果您混合使用 unicode
和 str
对象,您看到的错误将仅出现:
>>> utf8 = [u'\u0123'.encode('utf8'), u'\u0234'.encode('utf8')]
>>> ''.join(utf8)
'\xc4\xa3\xc8\xb4'
>>> u''.join(utf8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)
>>> ''.join(utf8 + [u'unicode object'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)
当使用 Unicode 值 u''
作为连接符,并分别将 Unicode 字符串添加到要连接的字符串列表时,会引发上述异常。
关于python 2.7 string.join() 与 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14758705/