转 python中包含UTF-8编码中文的列表或字典的输出

来源:互联网 发布:python中split函数 编辑:程序博客网 时间:2024/06/11 05:38

在python 下面一个包含中文字符串的列表(list)或字典,直接使用print会出现以下的结果:

dict = {"asdf": "我们的python学习"}
print dict
{'asdf': '\xe6\x88\x91\xe4\xbb\xac\xe7\x9a\x84python\xe5\xad\xa6\xe4\xb9\xa0'}
在输出处理好的数据结构的时候很不方便,需要使用以下方法进行输出:
import json
print json.dumps(dict, encoding="UTF-8", ensure_ascii=False)
{"asdf": "我们的python学习"}
注意上面的两个参数

还有如下例子:

>>> li=['sd','你好']
>>> print li
['sd', '\xe4\xbd\xa0\xe5\xa5\xbd']
>>> li[1].decode('gbk')
u'\u6d63\u72b2\u30bd'
>>> li[1].decode('utf-8')
u'\u4f60\u597d'
>>> unicode(li[1],'gbk')
u'\u6d63\u72b2\u30bd'
>>> li[1].decode('gb2312')
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 2-3: illegal multibyte sequence

解释:
>>> li=['sd','你好']
... print li
['sd', '\xe4\xbd\xa0\xe5\xa5\xbd']
>>> print li[1]
你好
>>>

输出十六进制数不是乱码:
不是乱码啊,这是 unicode 字符串在内存中的形式,python 在命令行界面输出的数据,如果不是ASCII码,则会以十六进制形式输出。需要比较中文的话,直接比较即可。
假如你将 li 写入一个文件 a.txt,你用笔记本打开 a.txt 时就可以看到正常的中文。
0 0
原创粉丝点击