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?

有帮助吗?

解决方案

Use built-in ascii:

print(ascii(context))

It works similarly to repr in Python 2.

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

>>> repr('\xb6')
"'¶'"
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top