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’


相关文章
|
9月前
|
存储 人工智能 Python
[oeasy]python061_如何接收输入_input函数_字符串_str_容器_ 输入输出
本文介绍了Python中如何使用`input()`函数接收用户输入。`input()`函数可以从标准输入流获取字符串,并将其赋值给变量。通过键盘输入的值可以实时赋予变量,实现动态输入。为了更好地理解其用法,文中通过实例演示了如何接收用户输入并存储在变量中,还介绍了`input()`函数的参数`prompt`,用于提供输入提示信息。最后总结了`input()`函数的核心功能及其应用场景。更多内容可参考蓝桥、GitHub和Gitee上的相关教程。
144 0
|
存储 索引 Python
Python中的str类型
Python中的str类型
785 2
|
TensorFlow 算法框架/工具 Python
【Tensorflow 2】解决'Tensor' object has no attribute 'numpy'
解决'Tensor' object has no attribute 'numpy'
311 3
|
并行计算 Serverless API
函数计算操作报错合集之出现 "AttributeError: 'NoneType' object has no attribute 'pop'" 错误,是什么原因
在使用函数计算服务(如阿里云函数计算)时,用户可能会遇到多种错误场景。以下是一些常见的操作报错及其可能的原因和解决方法,包括但不限于:1. 函数部署失败、2. 函数执行超时、3. 资源不足错误、4. 权限与访问错误、5. 依赖问题、6. 网络配置错误、7. 触发器配置错误、8. 日志与监控问题。
432 1
|
API C++ Python
【Azure 应用服务】Python fastapi Function在Azure中遇见AttributeError异常(AttributeError: 'AsgiMiddleware' object has no attribute 'handle_async')
【Azure 应用服务】Python fastapi Function在Azure中遇见AttributeError异常(AttributeError: 'AsgiMiddleware' object has no attribute 'handle_async')
134 0
|
TensorFlow API 算法框架/工具
【Tensorflow+keras】解决使用model.load_weights时报错 ‘str‘ object has no attribute ‘decode‘
python 3.6,Tensorflow 2.0,在使用Tensorflow 的keras API,加载权重模型时,报错’str’ object has no attribute ‘decode’
218 0
|
机器学习/深度学习 缓存 安全
Python标准库中的`str`类型有一个`translate()`方法,它用于替换字符串中的字符或字符子集。这通常与`str.maketrans()`方法一起使用,后者创建一个映射表,用于定义哪些字符应该被替换。
Python标准库中的`str`类型有一个`translate()`方法,它用于替换字符串中的字符或字符子集。这通常与`str.maketrans()`方法一起使用,后者创建一个映射表,用于定义哪些字符应该被替换。
|
Python 容器
一文让你彻底搞懂 Python 中 __str__ 和 __repr__
我们都知道,Python 的内置函数 ​​repr()​​ ​能够把对象用字符串的形式表达出来,方便我们辨认。这就是“字符串表示形式”。​​repr()​​​ 就是通过​ ​__repr__​​ ​这个特殊方法来得到一个对象的字符串表示形式的。
Python----魔法函数__str__/__repr__的用法
Python----魔法函数__str__/__repr__的用法
167 0

推荐镜像

更多