Python3 ‘str‘ object has no attribute ‘decode‘. Did you mean: ‘encode‘?

简介: Python3 ‘str‘ object has no attribute ‘decode‘. Did you mean: ‘encode‘?
  • AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?
    原因:一般是因为 str 的类型本身不是 bytes,所以不能解码。
  • 这是由于 py2py3 字符串 编码上的区别 导致的。
# 这是 py2 的写法
name = "中国"
name_utf8 = name.decode('utf-8')
print(name, name_utf8)
# 输出:中国 中国
# 这是 py3 的写法
name = "中国"
name_bytes = name.encode('utf-8')
name_utf8 = name_bytes.decode('utf-8')
print(name, name_bytes, name_utf8)
# 输出:中国 b'\xe4\xb8\xad\xe5\x9b\xbd' 中国
# 不填使用默认编码格式
name = "中国"
name_bytes = name.encode()
name_utf8 = name_bytes.decode()
print(name, name_bytes, name_utf8)
## 概念:
1、普通 str:可理解的语义。
2、字节流 str(bytes):0101010101,字节类型其实就是 2 进制格式,
   不过为了易于理解和计算,通常用 16 进制来表示,
   也就是 b'\xe4\xb8\...,b 开头代表是 bytes 类型。
## 语法
1、Encode(编码):把普通字符串 转为 机器可识别的 bytes。
2、Decode(解码):把bytes转为字符串。
## 语法记忆小技巧
1、编码 encode,就是把你认识的转为机器认识的。
2、解码 decode,就是把机器认识的解释为人能读懂的。
## 差异
1、py3 的 str 默认不是 bytes,所以不能 decode,只能先 encode 转为 bytes,再 decode。
2、py2 的 str 默认是 bytes,所以能 decode。
## 结论
所以 str.decode 本质是 bytes 类型的 str 的 decode
py3 经常出现 AttributeError: ‘str’ object has no attribute ‘decode’


相关文章
|
1月前
|
存储 Python
Python中encode和encoding的区别
Python中encode和encoding的区别
53 0
|
1月前
|
计算机视觉 Python
解决 NoneType‘ object has no attribute ‘astype’ 问题
解决 NoneType‘ object has no attribute ‘astype’ 问题
48 0
|
1月前
|
索引 Python
python字符串(str)
【5月更文挑战第8天】
23 3
|
10天前
|
Python
【已解决】AttributeError: ‘Index‘ object has no attribute ‘to_list‘
【已解决】AttributeError: ‘Index‘ object has no attribute ‘to_list‘
6 0
|
1月前
|
机器学习/深度学习 监控 数据可视化
【已解决】 ‘Conv2d’ object has no attribute ‘register_full_backward_hook’
【已解决】 ‘Conv2d’ object has no attribute ‘register_full_backward_hook’
|
1月前
|
安全 计算机视觉 Python
【已解决】attributeerror: ‘FreeTypeFont‘ object has no attribute ‘getsize‘
【已解决】attributeerror: ‘FreeTypeFont‘ object has no attribute ‘getsize‘
|
1月前
AttributeError: 'NoneType' object has no attribute 'to_capabilities'
AttributeError: 'NoneType' object has no attribute 'to_capabilities'
410 0
|
1月前
|
算法 开发者 Python
【Python 基础扫盲 】self参数、__init__方法和.__str__方法的用处和区别?
【Python 基础扫盲 】self参数、__init__方法和.__str__方法的用处和区别?
38 0
|
1月前
|
存储 设计模式 Python
Python中的类(Class)和对象(Object)
Python中的类(Class)和对象(Object)
48 0
|
1月前
|
编解码 Python Windows
Python写入文件报错‘gbk’ codec can’t encode character的解决办法
Python写入文件报错‘gbk’ codec can’t encode character的解决办法
96 2