简体   繁体   中英

How to catch unicodedecode error python?

How do you catch a unicodedecode error encountered in python and print out what the offending string is?

ie "... can't decode byte XXXX in position 8: invalid start byte"

This should get you started:

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))

Result:

args=('utf8', '\xfeFEF', 0, 1, 'invalid start byte')
encoding='utf8'
end=1
message=''
object='\xfeFEF'
reason='invalid start byte'
start=0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM