0
点赞
收藏
分享

微信扫一扫

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://www.runoob.com/python/att-string-decode.html​​



举报

相关推荐

0 条评论