Python Chinese garbled code solution
- 2020-04-02 13:13:57
- OfStack
Reason for garbled code:
The source file is encoded in utf-8, but the native default encoding of the window is GBK, so printing utf-8 strings directly from the console is of course garble!
Solutions:
1, print mystr. Decode (' utf-8). Encode (' GBK ')
2. General methods:
The import sys
Type = sys. Getfilesystemencoding ()
Print mystr. Decode (' utf-8) encode (type)
1. Python list or dictionary output garbled code solution
Problem: lists or dictionaries in Python contain Chinese strings, and using print directly results in the following:
# Print dictionary
dict = {'name': ' Zhang SAN '}
print dict
>>>{'name': 'xe5xbcxa0xe4xb8x89'}
# Print the list
list = [{'name': ' Zhang SAN '}]
print list
>>>[{'name': 'xe5xbcxa0xe4xb8x89'}]
Solutions:
Output using the following methods:
import json
# Print dictionary
dict = {'name': ' Zhang SAN '}
print json.dumps(dict, encoding="UTF-8", ensure_ascii=False)
>>>{'name': ' Zhang SAN '}
# Print the list
list = [{'name': ' Zhang SAN '}]
print json.dumps(list, encoding="UTF-8", ensure_ascii=False)
>>>[{'name': ' Zhang SAN '}]
2. UnicodeEncodeError in Python2.7: 'ASCII' codec can't encode exception error
# Reset encoding
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
Above is the python Chinese garble solution to the detailed content, more information about python garble please pay attention to this site other related articles!