python 2.7 string.join() 与 unicode

标签 python unicode

我有一堆字节字符串(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() 连接字节串效果很好;如果您混合使用 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 字符串添加到要连接的字符串列表时,会引发上述异常。

关于python 2.7 string.join() 与 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14758705/

相关文章:

linux - 十六进制转义为文本(UTF-8)、bash 脚本

c# - 允许在正则表达式中使用希伯来字母

python - Pymunk -- 查找物体的相关形状和约束

python - sha 模块已弃用

python - 如何从txt文件导入数据到django的数据库(mysql)

django - 如何在 Django 1.5 中获得对 rfc6532(电子邮件地址地址部分中的 unicode)的支持?

python - 有什么方法可以在python中将路径附加到环境变量 'PATH'

python - 如何检查任何给定集合中是否存在值

regex - 使用 Perl 发出匹配重音字符

java - 为什么c#和java unicode不同