Python displays the Unicode encoding in the dictionary as Chinese characters

In order to see the comfortable printing log in the log, you need to understand the unicode

In Python, a list or dictionary containing Chinese character strings, if you use print directly, the following results will appear:

>>> 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学习"}

----------ensure_ascii=False is more critical

Chinese encoding problem caused by ensure_ascii parameter in python json.dumps

One thing to be aware of when using json.dumps

>>> import json
>>> print json.dumps('中国')
"\u4e2d\u56fd"

输出的会是
'中国' 中的ascii 字符码,而不是真正的中文。

这是因为json.dumps 序列化时对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False>>> import json
>>> print json.dumps('中国')
"\u4e2d\u56fd"
>>> print json.dumps('中国',ensure_ascii=False)
"中国"
>>> 

Guess you like

Origin blog.csdn.net/iuv_li/article/details/127533633