1

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

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

1
  • Post the entire traceback. Commented Jan 8, 2013 at 13:37

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.