Python programming, a way to set utf-8 as the default encoding

Python's default encoding is ASCII, and you can view the default encoding through sys.getdefaultencoding().
When non-asc encoding appears in the program, python processing often has garbled errors. Generally, there are several methods as follows:

1. Temporary code changes

import sys  
reload(sys)  
sys.setdefaultencoding('utf8')  

It only takes effect temporarily when the program is executed, and the system default code has not changed.

If there is still an encoding error at this time, encode('utf-8') needs to be used to explicitly declare the encoding of the string.

字符串.encode('utf-8')

2. Catalog file changes

Create a file called sitecustomize.py, because python will load this file when it starts. If you want to modify some startup variables, you can write the operation in this file.

first step:

Create a new sitecustomize.py file in the Lib\site-packages folder of the python installation directory

The second step:

Fill in the following code in sitecustomize.py

# encoding=utf8  
import sys  
  
reload(sys)  
sys.setdefaultencoding('utf8') 

Guess you like

Origin blog.csdn.net/qq_43307934/article/details/109402051