Import sys in Python; reload(sys); sys.setdefaultencoding("utf-8")

  • python2

When installing python2, the default encoding is ascii. When a non-ascii encoding appears in the program, the python interpreter will report an error:

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

The python interpreter cannot handle non-ascii encoding. At this time, we need to set the python default encoding, which is generally set to utf-8 encoding format. Add the following code to the program to set the encoding to utf-8.

import sys
reload(sys)
sys.setdefaultencoding("utf-8")

The Python3 system uses utf-8 encoding by default. Therefore, for the case of using Python3, the above code is not needed, and it does not make any practical sense to do so.

  • python3

In addition, since there is no obvious difference between str and byte in Python2, it is often necessary to rely on defaultencoding for conversion; and there is a clear distinction between str and byte in python3, and conversion from one type to another must be explicit Specify encoding. But you can still use the following method instead of import sys; reload(sys).

import importlib,sys
importlib.reload(sys)

Guess you like

Origin blog.csdn.net/yjk13703623757/article/details/105720059