Python:如何强制pprint将Unicode字符串显示为字符串?

5

我正在使用unicode字符串(读取json输入的产物)美化一些数据结构,并希望将结果显示为字符串(即'foo'),而不是unicode字符串(即u'foo')。

在Python的pprint模块中,如何实现这一目标?

>>> pprint.pprint(u'hello')    # would prefer to see just 'hello'
u'hello'
1个回答

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.pprint(u'hello')
u'hello'
>>> mypprint.pprint(u'hello')
'hello'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接