UnicodeDecodeError,无效的连续字节 [英] UnicodeDecodeError, invalid continuation byte

查看:33
本文介绍了UnicodeDecodeError,无效的连续字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的项目失败了?为什么它以latin-1"成功?编解码器?

o = 对 xe9 字符的测试";#我希望这仍然是一个字符串,因为这是我收到的v = o.decode(utf-8")

结果:

 回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中.文件C:Python27libencodingsutf_8.py",第 16 行,在解码中返回 codecs.utf_8_decode(input, errors, True) UnicodeDecodeError:utf8"编解码器无法解码位置 10 中的字节 0xe9:连续字节无效

解决方案

在二进制中,0xE9 看起来像 1110 1001.如果您阅读维基百科上的UTF-8,您会看到这样的byte 后面必须跟两个 10xx xxxx 形式.因此,例如:

<预><代码>>>>b'xe9x80x80'.decode('utf-8')你'u9000'

但这只是异常的机械原因.在这种情况下,您的字符串几乎肯定是用 latin 1 编码的.您可以看到 UTF-8 和 latin 1 的不同之处:

<预><代码>>>>u'xe9'.encode('utf-8')b'xc3xa9'>>>u'xe9'.encode('latin-1')b'xe9'

(注意,我在这里混合使用 Python 2 和 3 表示.输入在任何版本的 Python 中都有效,但您的 Python 解释器不太可能以这种方式实际显示 unicode 和字节字符串.)

Why is the below item failing? Why does it succeed with "latin-1" codec?

o = "a test of xe9 char" #I want this to remain a string as this is what I am receiving
v = o.decode("utf-8")

Which results in:

 Traceback (most recent call last):  
 File "<stdin>", line 1, in <module>  
 File "C:Python27libencodingsutf_8.py",
 line 16, in decode
     return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError:
 'utf8' codec can't decode byte 0xe9 in position 10: invalid continuation byte

解决方案

In binary, 0xE9 looks like 1110 1001. If you read about UTF-8 on Wikipedia, you’ll see that such a byte must be followed by two of the form 10xx xxxx. So, for example:

>>> b'xe9x80x80'.decode('utf-8')
u'u9000'

But that’s just the mechanical cause of the exception. In this case, you have a string that is almost certainly encoded in latin 1. You can see how UTF-8 and latin 1 look different:

>>> u'xe9'.encode('utf-8')
b'xc3xa9'
>>> u'xe9'.encode('latin-1')
b'xe9'

(Note, I'm using a mix of Python 2 and 3 representation here. The input is valid in any version of Python, but your Python interpreter is unlikely to actually show both unicode and byte strings in this way.)

这篇关于UnicodeDecodeError,无效的连续字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆