Why does the 'str' object lack the 'decode' attribute error occur?

2026-05-16 15:261阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计494个文字,预计阅读时间需要2分钟。

Why does the 'str' object lack the 'decode' attribute error occur?

问题:如何改写伪原创以下代码段,不使用缩写,不超过100字?

原始代码:pythondef get_ch_label(txt_file): labels= with open(txt_file, 'rb') as f: for label in f: labels=labels + label.decode('UTF-8') return labels

改写后:python定义函数get_ch_label接收txt_file参数,初始化labels字符串变量为空,使用with语句以二进制读取模式打开txt_file文件,遍历文件中的每一行label,使用UTF-8解码后,将其添加到labels字符串中,并返回解码后的labels字符串。

问题

先上代码:

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'))

出现错误提示:

Why does the 'str' object lack the 'decode' attribute error occur?

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调用,是没有问题的!

引用

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



本文共计494个文字,预计阅读时间需要2分钟。

Why does the 'str' object lack the 'decode' attribute error occur?

问题:如何改写伪原创以下代码段,不使用缩写,不超过100字?

原始代码:pythondef get_ch_label(txt_file): labels= with open(txt_file, 'rb') as f: for label in f: labels=labels + label.decode('UTF-8') return labels

改写后:python定义函数get_ch_label接收txt_file参数,初始化labels字符串变量为空,使用with语句以二进制读取模式打开txt_file文件,遍历文件中的每一行label,使用UTF-8解码后,将其添加到labels字符串中,并返回解码后的labels字符串。

问题

先上代码:

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'))

出现错误提示:

Why does the 'str' object lack the 'decode' attribute error occur?

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调用,是没有问题的!

引用

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