在 Python 3 中打印非 ASCII 字符

Printing non-ascii characters in Python 3

所以我想打印特殊字符,如 ®(保留符号字符)。似乎很容易。我找到了 someone else trying to do the same thing 但带有版权符号并试了一下,但它出错了:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print('\u00a9')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python34\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in position 0: character maps to <undefined>

我之前在 Python 3.4.2 上遇到过这个问题,刚刚更新到 3.4.3,但似乎有同样的问题。

另一个需要注意的有趣的事情是 python 只有在我尝试打印这些字符时才会出错。如果我不打印它们,那么:

>>> a = '\xae'
>>> if a == '\xae':
...     print(True)
...
True

它只在您尝试打印到 windows cmd 时出错的原因是因为 cmd 本身不支持该字符。参见:

  1. this other stack overflow question 基本上问同样的事情。

  2. @Martijn Pieters 评论链接到 a python.org site addressing print failures,这解释了 Windows、

  3. 支持的字符现在 更天真了 OS,版权标志和保留标志不在此 设置.

这也解释了为什么它 仅在您尝试将它打印 到 cmd 时出错,但您仍然可以在布尔比较中使用它。不确定他们在 python 2.X 中究竟做了什么来让它发挥作用。

要打印这些字符,您可以使用:

ReservedSignChar = '®';
x = ReservedSignChar.encode('utf-8');
print(x);