Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Force pprint to display unicode strings as strings?

I am pretty-printing some data structures with unicode strings (an artifact of reading json input) and would prefer to see the results as strings, (i.e. 'foo') rather than as unicode strings (i.e. u'foo').

How can this be accomplished in the Python pprint module?

>>> pprint.pprint(u'hello')    # would prefer to see just 'hello'
u'hello'
like image 798
Mark Harrison Avatar asked Sep 02 '15 18:09

Mark Harrison


1 Answers

You can create your own PrettyPrinter object and override the format method.

import pprint

def no_unicode(object, context, maxlevels, level):
    """ change unicode u'foo' to string 'foo' when pretty printing"""
    if pprint._type(object) is unicode:
        object = str(object)
    return pprint._safe_repr(object, context, maxlevels, level)

mypprint = pprint.PrettyPrinter()
mypprint.format = no_unicode

Here's the output of the original and modified pprint.

>>> pprint.pprint(u'hello')
u'hello'
>>> mypprint.pprint(u'hello')
'hello'
like image 188
Mark Harrison Avatar answered Oct 12 '22 10:10

Mark Harrison