Python:强制pprint将unicode字符串显示为字符串?

Mar*_*son 5 python unicode pretty-print

我正在使用unicode字符串(读取json输入的工件)打印一些数据结构,并且更喜欢将结果看作字符串(即'foo')而不是unicode字符串(即u'foo').

如何在Python pprint模块中完成?

>>> pprint.pprint(u'hello')    # would prefer to see just 'hello'
u'hello'
Run Code Online (Sandbox Code Playgroud)

Mar*_*son 5

您可以创建自己的PrettyPrinter对象并覆盖该 format方法.

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
Run Code Online (Sandbox Code Playgroud)

这是原始和修改后的pprint的输出.

>>> pprint.pprint(u'hello')
u'hello'
>>> mypprint.pprint(u'hello')
'hello'
Run Code Online (Sandbox Code Playgroud)