Coding problems have always been a headache when programming with Python, and the program often encounters the following error message:
Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0x?? In position 1:ordinal not in range (128)
This is because Python's default encoding is ASCII at the time of installation, and when non-ASCII encoding occurs in the program, Python processing often reports the error above.
For the above problem, there are generally 2 kinds of treatment methods:
Method 1:
Add the following code block at the beginning of the Python code:
[Python]View PlainCopy
- Import Sys
- Reload (SYS)
- sys.setdefaultencoding (' UTF8 ')
This method is temporary and only takes effect when the program executes, and the system default encoding does not change.
Method 2:
The default encoding for Python installation is ASCII, and the default encoding can be viewed by sys.getdefaultencoding (). In order to solve the problem at once, we can modify Python's default encoding. Here's how:
The first step:
Create a new sitecustomize.py file under the Lib\site-packages folder in the Python installation directory
Step Two:
Fill in the following code in sitecustomize.py
- # Encoding=utf8
- Import Sys
- Reload (SYS)
- sys.setdefaultencoding (' UTF8 ')
Step three: Restart Python and view the default encoding via Sys.getdefaultencoding (), when the result is ' UTF8 '
Python settings Utf-8 as the default encoding