When Python is installed, the default encoding is ASCII, and when non-ASCII encoding occurs in the program, Python processing often reports such an error unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0x?? In position 1:ordinal No in range, Python does not handle non-ASCII encoding, it is necessary to set its own default encoding python, generally set to UTF8 encoding format.
Query system default encoding you can enter the following command in the interpreter:
Python code
>>>sys.getdefaultencoding ()
To set the default encoding, use:
Python code
>>>sys.setdefaultencoding (' UTF8 ')
It may be reported Attributeerror: ' Module ' object has no attribute ' setdefaultencoding ' error. Execute Reload (SYS), and then execute the above command to pass smoothly.
Then execute sys.getdefaultencoding () will find that the encoding has been set to UTF8, but the code modified in the interpreter can only guarantee that when the time is valid, after restarting the interpreter, it will be found that the encoding is reset to the default ASCII.
There are 2 ways to set the default encoding for Python:
A solution is to add the following code to the program:
Python code
# Encoding=utf8
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' UTF8 ')
Another option is to create a new sitecustomize.py under the Python lib\site-packages folder, with the following:
cd/usr/lib64/python2.7/site-packages/
chmod 755 sitecustomize.py
Python code
# Encoding=utf8
Import Sys
Reload (SYS)
Sys.setdefaultencoding (' UTF8 ')
Now restart the Python interpreter, execute sys.getdefaultencoding (), found that the encoding has been set to UTF8, after multiple restarts, the effect is the same, because the system when the Python boot, the file itself, set the system's default encoding, Without the need to manually add a solution to the code each time, is a solution.
Python2 (Chinese coding problem): Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0x?? In position 1