python格式化dict输出
来源:互联网 发布:网络打印机显示错误 编辑:程序博客网 时间:2024/05/16 12:57
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)
这种方法的缺点是不太美观
现在介绍另一种方法
如果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})
- python格式化dict输出
- python格式化dict输出
- python格式化输出dict等集合对象
- python中的格式化输出
- python 格式化输出
- python 格式化输出
- python格式化输出
- python 格式化输出
- Python 的格式化输出
- python 字符串格式化 输出
- Python格式化输出
- Python print 格式化输出
- python 格式化输出
- python 格式化输出
- python格式化输出
- python格式化输出
- python 格式化输出
- Python格式化输出
- doing
- 多表插入
- 『精品素材』35套免费的 Web & Mobile 界面设计套件《下集》
- OSX: 实用脚本程序(bash scripts)系列-19
- 数学之路(3)-数据分析(1)
- python格式化dict输出
- DirectX 性能优化
- Block编程值得注意的那些事儿
- ExtJs学习笔记 根据数据库生成动态多级树
- 不可见索引
- Effective C++ (01)
- 复杂的心情
- 函数索引
- hibernate中一对多等关系映射图和主键生成策略