Search code examples
python-3.xpython-unicode

Reliable `print(repr(context))` for Python 3


I am debugging a complex issue and need to see the content of structured variable named context. Attempt to print it with this code fails:

print(repr(context))

With error message:

UnicodeEncodeError: 'charmap' codec can't encode character '\xb6' in position
2336: character maps to <undefined>

What is the reliable way to print structured variables to the screen for debug in Python 3?


Solution

  • Use built-in ascii:

    print(ascii(context))
    

    It works similarly to repr in Python 2.

    >>> ascii('\xb6')
    "'\\xb6'"
    
    >>> repr('\xb6')
    "'¶'"