AttributeError: 'str' object has no attribute 'decode'

网友投稿 426 2022-08-23


AttributeError: 'str' object has no attribute 'decode'

问题

先上代码:

def get_ch_lable(txt_file): labels= "" with open(txt_file, 'rb') as f: for label in f: labels =labels+label.decode('UTF-8') return labels

想细致研究下decode方法。于是,切换到命令行下启动Python3,输入如下内容:

str = "this is string example....wow!!!"print ("Decoded String: " + str.decode('base64','strict'))

出现错误提示:

AttributeError: 'str' object has no attribute 'decode'

分析

默认情况下,Python3中str的类型本身不是bytes,所以不能解码!

这里有两个概念:

普通str:可理解的语义字节流str(bytes)(0101010101,可视化显示)

两个差异:

Python3的str 默认不是bytes,所以不能decode,只能先encode转为bytes,再decode。python2的str 默认是bytes,所以能直接调用decode。

于是,有结论:

str.decode 本质是bytes类型的str的decode!

python3经常出现 AttributeError: ‘str’ object has no attribute ‘decode’

如果您非要使用decode操作,则只能先encode转为bytes,再decode!

例外

在本文最开始处展示的代码中,因为以二进制方式打开并读取文件,所以,读取的label是bytes,因为可以直接使用decode调用,是没有问题的!

引用

​​https://blog.csdn.net/TineAine/article/details/116004584​​​​https://runoob.com/python/att-string-decode.html​​


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Spring Boot+RabbitMQ 通过fanout模式实现消息接收功能(支持消费者多实例部署)
下一篇:抖音web端 s_v_web_id 参数生成分析与实现(抖音web端_signature)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~