Search code examples
pythonunicodepretty-print

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'

Solution

  • 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'