我正在使用unicode字符串(读取json输入的产物)美化一些数据结构,并希望将结果显示为字符串(即'foo'),而不是unicode字符串(即u'foo')。
在Python的pprint模块中,如何实现这一目标?
>>> pprint.pprint(u'hello') # would prefer to see just 'hello'
u'hello'
我正在使用unicode字符串(读取json输入的产物)美化一些数据结构,并希望将结果显示为字符串(即'foo'),而不是unicode字符串(即u'foo')。
在Python的pprint模块中,如何实现这一目标?
>>> pprint.pprint(u'hello') # would prefer to see just 'hello'
u'hello'
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'