Python2.7 使用十六进制字符打印来自 unicode 的错误字符

Python2.7 prints wrong characters from unicode with hexadecimal chars

sys.getdefaultencoding()
-> utf8
test = u'tempête'
test
-> u'temp\xc3\xaate'
print(test)
-> tempête # WTF ?

sys.setdefaultencoding('ascii')
sys.getdefaultencoding()
-> ascii
test = u'tempête'
test
-> u'temp\xc3\xaate'
print(test)
-> tempête #...

当我从 pdb 执行 set_trace() 时,我观察到了这些结果。

在 python2.7 shell 我有正确的结果:

sys.getdefaultencoding()
-> ascii
test = u'tempête'
test
-> u'temp\xc3\xaate'
print(test)
-> tempête # WTF ?

我几个小时都在为此苦苦挣扎...

确保您的 locale 编码与您的终端仿真匹配。输入 locale 进行检查。

sys.setdefaultencoding() 与打印无关 - Python 使用您的语言环境来设置打印时使用的标准输出编码。参见 sys.stdout.encoding

我可以像这样部分复制你的问题:

  1. 将终端仿真设置为:UTF-8
  2. 将区域设置设置为 en_GB.ISO8859-1。 IE。不是 UTF-8

    export LANG=en_GB.ISO8859-1
    
  3. 运行 您的代码:

    >>> test = u'tempête'
    >>> test
    u'temp\xc3\xaate'
    

ê 变为 Ã (U+00C3) 和 ª(U+00AA) 的事实是问题的关键,表明 Python 认为 的编码应该是一个 8 位字符放。

我无法复制您的最终印刷品,但我怀疑摆弄 setdefaultencoding() 并煮熟了所有东西 - 请参阅我的回答,了解为什么这是个坏主意: