zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python编程:关于编码解码及UnicodeDecodeError

Python编码编程 关于 解码 unicodedecodeerror
2023-09-14 09:07:12 时间

python2默认的编码是ASCII码
python3默认的编码是utf-8

思路:先将现有编码转为unicode,再转为目标编码

encode() –> decode()

Created with Raphaël 2.1.2 asccii码 unicode utf-8
# -*- coding:gbk -*-

import sys

print(sys.getdefaultencoding())  # 获取默认编码方式
# ->utf-8

s = "你好"

print(s.encode("gbk"))  # 转为字节
# ->b'\xc4\xe3\xba\xc3'

print(s.encode("gb2312"))
# ->b'\xc4\xe3\xba\xc3'

print(s.encode("utf-8"))
# ->b'\xe4\xbd\xa0\xe5\xa5\xbd'

print(s.encode("utf-8").decode("utf-8")) # 转为字符
# ->你好

解决UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe5

Python的str默认是ascii编码,和unicode编码冲突,就会报这个标题错误。那么该怎样解决呢?

通过搜集网上的资料,自己多次尝试,问题算是解决了,在代码中加上如下几句即可。

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

参考:
https://blog.csdn.net/u010159842/article/details/54380523