解决编码问题:AttributeError: 'str' object has no attribute 'decode'

1. 问题发现:

出现:读取文件,对其进行解码,出现错误,AttributeError: 'str' object has no attribute 'decode'

解释:属性错误,str对象不包含‘decode’属性。

2.原因解释:

出现问题原因:str与bytes表示的是两种数据类型,str为字符串型,bytes为字节型。对str编码encode得到bytes,
对bytes解码得到str,两者互为转换。而上面出现问题的原因是对str字符串使用了解码,显然是猪头不对马尾。

3.解决方法:

解决办法:删除decode(‘utf-8’)

4.代码演示:

txt = '你好,shiyi,很感谢你陪伴我的日子'
#str->bytes encode
txt = txt.encode('utf-8')
print(type(txt))
#bytes->str decode
txt = txt.decode('utf-8')
print(type(txt))

5.结果展示:

<class 'bytes'>
<class 'str'>
Process finished with exit code 0



猜你喜欢

转载自www.cnblogs.com/maxxu11/p/12785872.html