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-8import pprint, cStringIOclass 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})