LastTigerEyes
LastTigerEyes

Reputation: 707

Printing non-ascii characters in Python 3

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

Upvotes: 1

Views: 3002

Answers (2)

Tenzin
Tenzin

Reputation: 2505

To print these characters you could use:

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

Upvotes: 2

LastTigerEyes
LastTigerEyes

Reputation: 707

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.

Upvotes: 2

Related Questions