使用 'iso-8859-1' 解码字节串是否会引发 UnicodeDecodeError

Does decoding a bytestring using 'iso-8859-1' ever raise UnicodeDecodeError

我有一些处理 HTTP header 的代码。 我知道 header 值 应该 在 ISO-8859-1 编码中, 尽管我想确保程序在不正常的情况下表现得很好。

最初我将解码包装在 try..catch 中用于 UnicodeDecodeError

try:
    value = header.decode('iso-8859-1')
except UnicodeDecodeError:
    ...

然而,当我开始测试这种行为时,我无法模拟错误情况。未定义为 the iso-8859-1 codepage 的字节似乎仍能成功解码。

>>> b'\x80'.decode('iso-8859-1')
u'\x80'

所以:

注意:针对Python 2.7 和 3.4 进行了测试。

看来不会给你带来问题:

In [1]: for i in xrange(9999):
   ...:     chr(i).decode('iso-8859-1')
   ...:     
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-c3c072235f24> in <module>()
      1 for i in xrange(9999):
----> 2     chr(i).decode('iso-8859-1')
      3 

ValueError: chr() arg not in range(256)