python - 统一码编码错误 : 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

标签 python python-2.7 utf-8 decode

<分区>

我只是想解码类似\uXXXX\uXXXX\uXXXX 的字符串。但是我得到一个错误:

$ python
Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\u041e\u043b\u044c\u0433\u0430'.decode('utf-8')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)

    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)

我是 Python 新手。有什么问题吗?谢谢!

最佳答案

Python 正在努力提供帮助。您无法解码 Unicode 数据,它已经被解码了。因此 Python 首先将对数据进行编码(使用 ASCII 编解码器)以获取要解码的字节。正是这种隐式编码失败了。

如果您有 Unicode 数据,则只有编码为 UTF-8 才有意义,而不是解码:

>>> print u'\u041e\u043b\u044c\u0433\u0430'
Ольга
>>> u'\u041e\u043b\u044c\u0433\u0430'.encode('utf8')
'\xd0\x9e\xd0\xbb\xd1\x8c\xd0\xb3\xd0\xb0'

如果您想要一个 Unicode 值,那么只需使用 Unicode 文字 (u'...') 即可。无需进一步解码。

同样的隐式转换发生在另一个方向;如果您尝试对字节串进行编码,则会触发隐式解码:

>>> u'\u041e\u043b\u044c\u0433\u0430'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)

关于python - 统一码编码错误 : 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28544686/

相关文章:

python - TensorFlow - tf.keras.layers.Layer 与 tf.keras.Model 之间的区别

python - 从具有重复键的 2 个列表创建字典

Python 默认区域设置(不支持的区域设置)

python - 如何将文字样式应用于 Richtext 对象? (docxtpl 库)

python - 如何从 html 表格行中提取文本

MySQL 检查 BLOB 是否为有效的 UTF-8

php - c2a0 和 20 字符串比较

python - pytorch Dataset.__getitem__ 是否必须返回字典?

python - libsvm的grid.py输出错误

python - pyopencl 示例设备错误