MichM MichM - 11 days ago 5
Python Question

Python 2.7 prints Unicode as a square box in the Python console

I use the latest Python 2 with pycharm on a Mac.

In the Python console, I noticed that if I do

print u'\u31d4'
, the Python console prints out a half square box, ㇔. So does
print u'\u31d2'
. But
should be a
stroke, as seen in http://unicode-table.com/en/search/?q=31d4; and
should be a different stroke, as in http://unicode-table.com/en/search/?q=31d2.


  1. What can I do so that the Python console prints out these strokes correctly?

  2. A related question: the Python console currently doesn't print out Unicode characters by default, unless I explicitly call
    . For example:

    (console prompt)>>> a = u'\u4e00'

    (console prompt)>>> a

The console prints out

Only if I explicitly use
print a
would I get
back. Can I change a setting somewhere so that it prints
in response to typing
in the console, without me having to call print?


Question 2

What is displayed by the interpreter is governed by the function sys.displayhook. Loosely speaking, the default display hook displays the repr of the value unless it is None.

To alter the displayhook simply set to another function. For example:

>>> a = u'\u4e00'
>>> import sys
>>> def my_display(x):
...     if isinstance(x, unicode):
...         sys.stdout.write(x.encode("utf-8"))
...     else:
...         sys.stdout.write(repr(x))
...     sys.stdout.write("\n")

>>> sys.displayhook = my_display
>>> a
>>> 一