定義字典并直接輸出,結果輸出結果中文是亂碼展示
1
2
|
d = { 'name' : 'lily' , 'age' : 18 , 'sex' : '女' , 'no' : 1121 } print d |
輸出結果:
{'age': 18, 'no': 1121, 'name': 'lily', 'sex': '\xe5\xa5\xb3'}
解決方法:
1
2
|
d = { 'name' : 'lily' , 'age' : 18 , 'sex' : '女' , 'no' : 1121 } print json.dumps(d,encoding = 'utf-8' ,ensure_ascii = False ) |
輸出結果:
{"age": 18, "no": 1121, "name": "lily", "sex": "女"}
內容擴展:
Python中列表或字典輸出亂碼的解決方法
問題: Python中的列表(list)或字典包含中文字符串,直接使用print會出現以下的結果:
1
2
3
4
5
6
7
8
9
|
#打印字典 dict = { 'name' : '張三' } print dict >>>{ 'name' : '\xe5\xbc\xa0\xe4\xb8\x89' } #打印列表 list = [{ 'name' : '張三' }] print list >>>[{ 'name' : '\xe5\xbc\xa0\xe4\xb8\x89' }] |
解決方案:
使用以下方法進行輸出:
1
2
3
4
5
6
7
8
9
10
11
|
import json #打印字典 dict = { 'name' : '張三' } print json.dumps( dict , encoding = "UTF-8" , ensure_ascii = False ) >>>{ 'name' : '張三' } #打印列表 list = [{ 'name' : '張三' }] print json.dumps( list , encoding = "UTF-8" , ensure_ascii = False ) >>>[{ 'name' : '張三' }] |
到此這篇關于python dict亂碼如何解決的文章就介紹到這了,更多相關python dict亂碼解決方法內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/faq/python/18558.html