【Python】AttributeError: ‘str‘ object has no attribute ‘decode‘解决方法
1. 引起问题的原因有两种原因:Python2和Python3在字符串编码上的区别。Python 3.4: str : AttributeError: ‘str’ object has no attribute 'decode2. encode与decode函数str与bytes表示的是两种数据类型,str为字符串型,bytes为字节型。对str编码encode得到bytes,对bytes解码得到
·
1. 引起问题的原因
有两种原因:
- Python2和Python3在字符串编码上的区别。
- 编码解码类型不一致
2. encode与decode函数
str
与bytes
表示的是两种数据类型,str为字符串型,bytes为字节型。对str编码encode得到bytes,对bytes解码得到str,两者互为转换。而上面出现问题的一种原因是对str字符串使用了解码,显然是猪头不对马尾。
txt = '你好,shiyi,很感谢你陪伴我的日子'
#str->bytes encode
txt = txt.encode('utf-8')
print(type(txt))
#bytes->str decode
txt = txt.decode('utf-8')
print(type(txt))
# results
<class 'bytes'>
<class 'str'>
Process finished with exit code 0
3. python2与python3的编码方式
- Python3的str 默认不是bytes,所以不能decode,只能先encode转为bytes,再decode
- python2的str 默认是bytes,所以能decode
4. 解决方法
- 对于第一种原因:删除decode(‘utf-8’)或者使用‘str’.encode(‘utf-8’). decode(‘utf-8’) 先编码成bytes,再解码成字符串
- 对于第二种:各种编码方式尝试解决:utf-8,gbk,ISO-8859-1,gb2312
更多推荐
已为社区贡献5条内容
所有评论(0)