string.decode自定义错误参数

bro*_*and 3 python

我有这个Python 2.7代码:

# coding: utf-8
#
f = open('data.txt', 'r')

for line in f:
  line = line.decode(encoding='utf-8', errors='foo23')
  print len(line)

f.close()
Run Code Online (Sandbox Code Playgroud)

为什么Python不会发出错误,因为错误的唯一有效/注册编解码器是:

  • 严格
  • 忽视
  • 更换
  • xmlcharrefreplace
  • backslashreplace

文件说,你可以自己注册,但我没有注册"foo23"和Python代码仍然没有一个错误/警告运行.如果我更改编码参数会引发错误,但如果我将错误更改为自定义字符串,则一切正常.

line = line.decode(encoding='utf-9', errors='foo23')

 File "parse.py", line 7, in <module>
line = line.decode(encoding='utf-9', errors='foo23')
LookupError: unknown encoding: utf-9
Run Code Online (Sandbox Code Playgroud)

jfs*_*jfs 6

如果在解码期间没有错误; 该errors参数未被使用,只要它是一个字符串,它的值无关紧要:

>>> b'\x09'.decode('utf-8', errors='abc')
u'\t'
Run Code Online (Sandbox Code Playgroud)

如果无法使用给定的编码解码字节,则使用错误处理程序,如果指定不存在的错误处理程序,则会出现错误:

>>> b'\xff'.decode('utf-8', errors='abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "../lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
LookupError: unknown error handler name 'abc'
Run Code Online (Sandbox Code Playgroud)