python中import sys ; reload(sys) ; sys.setdefaultencoding("utf-8")的作用

  • python2

在安装python2时,默认编码是ascii,当程序中出现非ascii编码时,python解释器会报错:

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

python解释器没法处理非ascii编码,此时我们需要设置python默认编码,一般设置为utf-8编码格式。在程序中加入以下代码,即可将编码设置为utf-8。

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

Python3系统默认使用的就是utf-8编码。所以,对于使用Python3的情况,就不需要以上代码了,这么做也不会有什么实际意义。

  • python3

另外,由于Python2中str和byte之间没有明显区别,经常要依赖于defaultencoding来做转换; 而在python3中有了明确的str和byte类型区别,从一种类型转换成另一种类型要显式指定encoding。但是仍然可以使用下面方法代替import sys ; reload(sys)。

import importlib,sys
importlib.reload(sys)

猜你喜欢

转载自blog.csdn.net/yjk13703623757/article/details/105720059
sys