How to print out Tree Structure?

How do you print a python unicode data structure?

  • I figured out how to print python unicode with Chinese characters on to a web page and see the characters: print u_char.encode('utf-8') But if i have a data structure that contains unicode strings, how can i print the data structure and see the characters (in python 2.7)? eg: pprint(data_struct) [ u"您好", "world" ]

  • Answer:

    You can do this in Python 2 by subclassing pprint.PrettyPrinter: # coding=utf-8 import pprint _escape = dict((q, dict((c, unicode(repr(chr(c)))[1:-1]) for c in range(32) + [ord('\\')] + range(128, 161), **{ord(q): u'\\' + q})) for q in ["'", '"']) class MyPrettyPrinter(pprint.PrettyPrinter): def format(self, object, context, maxlevels, level): if type(object) is unicode: q = "'" if "'" not in object or '"' in object \ else '"' return ("u" + q + object.translate(_escape[q]) + q, True, False) return pprint.PrettyPrinter.format( self, object, context, maxlevels, level) pp = MyPrettyPrinter() pp.pprint([u"您好", 'world']) Python 3 does what you want out-of-the-box: Python 3.2.2 (default, Sep 5 2011, 21:17:14) [GCC 4.6.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pprint >>> pprint.pprint(["您好", "world"]) ['您好', 'world']

Anders Kaseorg at Quora Visit the source

Was this solution helpful to you?

Other answers

When you try to print a data structure in Python it will print the source code representation of the elements inside, which for Unicode strings will print quotes and escape non-ASCII characters inside. What it prints is not incorrect, it is a text representation that accurately represents the Python objects. However, you want Unicode strings to be printed by encoding them in UTF-8 instead. I would suggest that you not use pprint or print to print data structures to a web page, since it is not very user-friendly to display things that look like Python data structures on a web page. You should instead either write your own formatting function that iterates through the data structure and prints elements the way you want, or maybe use some library that is specially designed to format Python data structures nicely on a web page.

Xuan Luo

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.