如何捕获unicodedecode错误python?

Rol*_*ndo 1 python

如何捕获 python 中遇到的 unicodedecode 错误并打印出有问题的字符串是什么?

即“...无法解码位置 8 中的字节 XXXX:无效的起始字节”

geo*_*org 6

这应该可以帮助您开始:

try:
    s = '\xFEFEF'
    u = s.decode('utf8')
except UnicodeDecodeError as e:
    for p in dir(e):
        if not p.startswith('_'):
            print '%s=%r' % (p, getattr(e, p))
Run Code Online (Sandbox Code Playgroud)

结果:

args=('utf8', '\xfeFEF', 0, 1, 'invalid start byte')
encoding='utf8'
end=1
message=''
object='\xfeFEF'
reason='invalid start byte'
start=0
Run Code Online (Sandbox Code Playgroud)