Printing non-ascii characters in Python 3

对着背影说爱祢 提交于 2019-12-13 18:14:33

问题


So I want to print special characters like ® (the Reserved Sign char). Seems easy enough. I found someone else trying to do the same thing but with the copyright symbol and gave it a whirl, but it errored out:

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>

I was previously having this issue on Python 3.4.2, and just updated it to 3.4.3, but it seems to be having the same problem.

The other interesting thing to note is that python only errors out when I try to print these characters. If I leave them unprinted, then:

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

回答1:


To print these characters you could use:

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



回答2:


The reason it only errors out when you try to print to windows cmd is because cmd itself does not support that character. See:

  1. this other stack overflow question asking basically the same thing.

  2. @Martijn Pieters comment linking to a python.org site addressing print failures, which explains that on Windows,

  3. the supported characters are now more naitive to the OS, and the Copyright Sign and Reserve Sign are not in this set.

This also explains why it only errors out when you try to print it to cmd, but you can still use it in boolean comparisons. Not sure what exactly they did in python 2.X to get it functional.



来源:https://stackoverflow.com/questions/30470483/printing-non-ascii-characters-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!