Skip to content

Instantly share code, notes, and snippets.

@bakyeono
Last active February 18, 2018 18:48
Show Gist options
  • Save bakyeono/457409f5d7994568da67 to your computer and use it in GitHub Desktop.
Save bakyeono/457409f5d7994568da67 to your computer and use it in GitHub Desktop.
Python2 - PrettyPrinter가 유니코드 출력하도록 하기

Python2 - PrettyPrinter가 유니코드 출력하도록 하기

출처: http://www.quora.com/How-do-you-print-a-python-unicode-data-structure

# 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'유니코드')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment