Home  >  Article  >  Backend Development  >  How to set python utf-8 encoding

How to set python utf-8 encoding

silencement
silencementOriginal
2019-06-13 10:31:5113858browse

How to set python utf-8 encoding

When using Python to program, coding problems have always been a headache. The following error message is often encountered in the program:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128)

This is because python is installed during installation. , the default encoding is ascii. When non-ascii encoding appears in the program, python processing will often report the above error.

For the above problem, there are generally two ways to deal with it:

Method 1:

Add the following code block at the beginning of the python code:

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

This method is temporary and only takes effect when the program is executed. The system default encoding has not changed.

Method 2

The default encoding when python is installed is ascii, and you can view the default encoding through sys.getdefaultencoding(). In order to solve the problem once and for all, we can modify python's default encoding. The specific operations are as follows:

The 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')

Step 3: Restart python and check the default encoding through sys.getdefaultencoding(). The result is 'utf8'

The above is the detailed content of How to set python utf-8 encoding. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn