pprint:UnicodeEncodeError:'ascii'编解码器无法编码字符

use*_*786 0 python dictionary pprint

这让我发疯。.我正在尝试使用'é'char来复制字典,并且使用Python 3将我扔掉了。

    from pprint import pprint
    knights = {'gallahad': 'the pure', 'robin': 'the bravé'}
    pprint (knights)
Run Code Online (Sandbox Code Playgroud)

错误

File "/data/prod_envs/pythons/python36/lib/python3.6/pprint.py", line 176, in _format
stream.write(rep)
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 43: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我阅读了Python ASCII文档,但似乎没有解决此问题的快速方法,除了将dict拆开,然后通过'.encode'将有问题的值重写为ASCII值,然后重新组装dict再次

我有什么办法可以在不拆开字典的情况下打印出来?

谢谢 !

Ser*_*sta 5

这是无关的pprint:模块只格式化的字符串转换成另一个字符串,然后经过格式化的字符串的基础流。因此,将é字符(U + 00E9)写入stdout 时会发生错误。

现在,它实际上取决于底层操作系统和Python解释器的配置。在Linux或其他类似Unix的系统中,您可以通过PYTHONIOENCODING在启动Python之前设置环境变量来尝试在终端会话中声明UTF-8或Latin1字符集:

$ export PYTHONIOENCODING=Latin1
$ python
Run Code Online (Sandbox Code Playgroud)

(或PYTHONIOENCODING=utf8根据终端或终端窗口的实际编码使用)。