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

时间:2015-09-02 18:20:18

标签: python unicode pretty-print

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

如何在Python pprint模块中实现?

>>> pprint.pprint(u'hello')    # would prefer to see just 'hello'
u'hello'

1 个答案:

答案 0 :(得分: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

这是原始和修改过的pprint的输出。

>>> pprint.pprint(u'hello')
u'hello'
>>> mypprint.pprint(u'hello')
'hello'