解决编码问题: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

 



 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM