python格式化dict输出

python格式化dict输出
如果dict里有unicode or utf-8编码的字符串,缺省是:
In [75]: dd = { 'name': u'功夫熊猫' }
In [76]: dd
Out[76]: {'name': u'\u529f\u592b\u718a\u732b'}

In [77]: dd2 = { 'name': '功夫熊猫' }
In [78]: dd2
Out[78]: {'name': '\xe5\x8a\x9f\xe5\xa4\xab\xe7\x86\x8a\xe7\x8c\xab'}

输出中文不直观,有一种方法是把dict转化成josn格式的字符串输出
print simplejson.dumps(dd, ensure_ascii=False)
这种方法的缺点是不太美观
现在介绍另一种方法

#coding=utf-8

import pprint, cStringIO

class UniPrinter(pprint.PrettyPrinter):        
    def format(self, obj, context, maxlevels, level):
        if isinstance(obj, unicode):
            out = cStringIO.StringIO()
            out.write('u"')
            for c in obj:
                if ord(c)<32 or c in u'"\\':
                    out.write('\\x%.2x' % ord(c))
                else:
                    out.write(c.encode("utf-8"))
                
            out.write('"')
            # result, readable, recursive
            return out.getvalue(), True, False
        elif isinstance(obj, str):
            out = cStringIO.StringIO()
            out.write('"')
            for c in obj:
                if ord(c)<32 or c in '"\\':
                    out.write('\\x%.2x' % ord(c))
                else:
                    out.write(c)
                
            out.write('"')
            # result, readable, recursive
            return out.getvalue(), True, False
        else:
            return pprint.PrettyPrinter.format(self, obj,
                context,
                maxlevels,
                level)        

#UniPrinter().pprint({ u'k"e\\y': u'我爱ä¸*国人' })
print { 'name': u'功夫熊猫' }
UniPrinter().pprint({ 'name': u'功夫熊猫' })
UniPrinter().pprint({'name': '\xe5\x8a\x9f\xe5\xa4\xab\xe7\x86\x8a\xe7\x8c\xab'})
UniPrinter().pprint({'name':'\xe5\x8a\x9f\xe5\xa4\xab\xe7\x86\x8a\xe7\x8c\xab', 'age':22, 'address':'yydg.com.cn', 'male':True})


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值