Python 2.7中使用unicode的string.join()函数

13

我有一堆字节串(在Python 2.7中是str而不是unicode),其中包含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() 方法?当然我可以在循环中连接它们,但这不是一种高效的方式。

2个回答

17
使用''.join()连接字节字符串完全没有问题;您看到的错误只会出现在混合使用unicodestr对象时:
>>> 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字符串添加到要连接的字符串列表中时,将引发上述异常。


1
如何将“unicode”和“str”对象分开? - fiona
1
@fiona 决定将你的字节字符串转换为 Unicode,然后连接起来。最好尽早进行解码,仅在完成文本并必须将其传递给仅接受字节的内容时才进行编码。 - Martijn Pieters

2

"".join(...) 只有当每个参数都是 str 类型(无论编码方式如何)时才能正常工作。

你看到的问题可能与 join 函数本身无关,而是你提供给它的数据有问题。请发更多代码以便我们找出真正的问题所在。


1
感谢您的帮助。utf8_strings 是由 xlrd 加载的数据。xlrd 是一个非常棒的 Python 模块,幸运的是它返回所有(非数字)数据都是 unicode 类型。我对它们进行了一些操作,但似乎有些变成了 str 类型。 - thkang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接