SoFunction
Updated on 2024-10-29

Python Chinese garbled code solution

Reason for garbling:

The encoding format of the source code file is utf-8, but window's local default encoding is gbk, so in the console directly print the utf-8 string is of course garbled!

Solution:

1、print ('utf-8').encode('gbk')
2. A more generalized approach:

import sys
type = ()
print ('utf-8').encode(type)

1. Python list or dictionary output garbled solution

Problem: A list or dictionary in Python contains Chinese strings, and using print directly produces the following result:

#Print the dictionary
dict = {'name': 'Zhang San'}
print dict
>>>{'name': '\xe5\xbc\xa0\xe4\xb8\x89'}

#Print List
list = [{'name': 'Zhang San'}]
print list
>>>[{'name': '\xe5\xbc\xa0\xe4\xb8\x89'}]

Solution:
Use the following methods for output:

import json

#Print the dictionary
dict = {'name': 'Zhang San'}
print (dict, encoding="UTF-8", ensure_ascii=False)
>>>{'name': 'Zhang San'}

#Print List
list = [{'name': 'Zhang San'}]
print (list, encoding="UTF-8", ensure_ascii=False)
>>>[{'name': 'Zhang San'}]

2. Python 2.7 UnicodeEncodeError: 'ascii' codec can't encode exception error

# Reset encoding format
import sys
reload(sys)
('utf-8')

Above is the solution to python Chinese garbled details, more information about python garbled please pay attention to my other related articles!