0

I'm rather new at Python and am experiencing some issues printing the contents of an Exception:

# -*- coding: ISO-8859-1 -*-

    except Exception as err:
    print(err)

yields "UnicodeEncodeError: 'ascii' codec can't encode character u'\uf260' in position 52: ordinal not in range(128)"

I've tried reading https://docs.python.org/2.7/howto/unicode.html#the-unicode-type but the issue I'm encountering is that in order to decode and encode or use unicode(..,errors='ignore') I need a string and str(err) fails with the above error message.

This is in a Windows environ. Thankful for any replies, even if it is "learn to search!" because in that case there was indeed a similar question that I missed while searching that's hopefully been answered : )

Edit. I've tried

print("Error {0}".format(str(err.args[0])).encode('utf-8', errors='ignore'))

which yields exactly the same error message.

David I
  • 31
  • 1
  • 5

1 Answers1

0

UnicodeEncodeError: 'ascii' codec can't encode character u'\uf260' in position 52: ordinal not in range(128)

Look in the error, character \uf260 its not ascii, but something is trying to treat a non-ascii character as ascii. What?

Try this instead : print err.__repr__() .

Explanation:

err is an Exception object which has __str__() function implemented, so on printing an object object.__str__() method is called which essentially brings this error. You can verify by calling print err.__str__() to get similar error.

Also to check that Exception class module has __str__(), you can do dir(Exception).

Update: Check this link to understand how print picks up encoding.

References:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Python __str__ versus __unicode__

How to print a class or objects of class using print()?

Python: Converting from ISO-8859-1/latin1 to UTF-8

Why does Python print unicode characters when the default encoding is ASCII?

รยקคгรђשค
  • 1,919
  • 1
  • 10
  • 18
  • Thanks for your reply! Yes, what you listed under Try this instead: gave the same error. In the end I converted the exception object to a string with repr() and then printed it. Am not sure where the weird "J" character came from but the error conveyed was nevertheless helpful. – David I Feb 19 '18 at 09:26
  • Okay, sorry that I assumed that your string will be unicode ... the message you are printing is neither Unicode nor Ascii. So you need to use object.__repr__() method (aka repr(object)) or convert the message in this way: [convert from one format to another](https://stackoverflow.com/questions/6539881/python-converting-from-iso-8859-1-latin1-to-utf-8) ... I have updated the same in answer. – รยקคгรђשค Feb 26 '18 at 03:13