Python: 打印重音字符时出现 UnicodeEncodeError

Python: UnicodeEncodeError when printing accented characters

使用 Python 2.7.11

#!/usr/bin/python
# -*- coding: utf-8 -*-
print 'ÁÉŐÜŐ'
print u'ÁÉÖÜŐ'

结果如下:

ÁÉŐÜŐ
    Traceback (most recent call last):
        File "C:\Users\RaseR\Desktop\testing.py", line 4, in <module>
            print u'ÁÉÖÜŐ'
        File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
            return codecs.charmap_encode(input,errors,encoding_map)
    UnicodeEncodeError: 'charmap' codec can't encode character u'\u0150' in 
    position 4: character maps to <undefined>

如有必要:

编码为 UTF-8 的 Notepad++

Windows 10 控制台 w/ Lucida 控制台字体

当您 print 时,您正在打印到标准输出。标准输出使用某种编码,所有内容都必须转换为该编码。

就我而言:

>>> sys.stdout.encoding
'cp852'
>>> u'\u0150'.encode(sys.stdout.encoding)
'\x8a'
>>> print u'\u0150'
Ő
>>> print '\x8a'
Ő

在您的情况下,stdout 使用的编码中似乎不存在 Ő 字符,因此转换失败。无法打印。

您可以手动对其进行编码,指定如何处理无法编码的字符:

>>> print u'\u0150'.encode(sys.stdout.encoding, 'replace')
Ő

带有无法编码的字符:

>>> print u'\u0150\u1234'.encode(sys.stdout.encoding, 'replace')
Ő?