Python报错:TypeError: a bytes-like object is required, not ‘str‘

简介: Python报错:TypeError: a bytes-like object is required, not ‘str‘

Python报错:TypeError: a bytes-like object is required, not ‘str‘


Table of Contents

一、问题

二、问题原因

三、解决办法

四、额外补充

1、str to bytes

2、bytes to str

一、问题

TypeError: a bytes-like object is required, not 'str'

二、问题原因

原因是 Python3 和 Python2 在套接字返回值解码上有区别。

这里简单解释一下套接字。套接字就是 socket,用于描述 IP 地址和端口,应用程序通过套接字向网络发出请求或者应答网络请求,可以认为是计算机网络的数据接口。目前套接字分为两种:基于文件型和基于网络型。

三、解决办法

使用函数 encode() 和 decode():

1、str 通过 encode() 函数编码为 bytes

2、bytes 通过 decode() 函数编码为 str。(当我们从网络或磁盘上读取了字节流,则读到的数据就是 bytes)

四、额外补充

1、str to bytes

先声明一个字符串 s:

四种转换方式:

2、bytes to str

声明一个 bytes:

三种转换方式:

以上,问题解决~

相关文章
|
8月前
|
索引 Python
Python错误 - 'list' object is not callable 的问题定位与解决
出现编程问题并不可怕,关键在于是否可以从中学习与成长。遇到'list' object is not callable这样的错误,我们不仅需要学会应对,更需要了解其背后的原因,避免类似的问题再次出现。记住,Python的强大功能和灵活性同时也意味着我们需要对其理解更准确,才能更好的使用它。
974 70
|
11月前
|
存储 人工智能 Python
[oeasy]python061_如何接收输入_input函数_字符串_str_容器_ 输入输出
本文介绍了Python中如何使用`input()`函数接收用户输入。`input()`函数可以从标准输入流获取字符串,并将其赋值给变量。通过键盘输入的值可以实时赋予变量,实现动态输入。为了更好地理解其用法,文中通过实例演示了如何接收用户输入并存储在变量中,还介绍了`input()`函数的参数`prompt`,用于提供输入提示信息。最后总结了`input()`函数的核心功能及其应用场景。更多内容可参考蓝桥、GitHub和Gitee上的相关教程。
279 0
|
C++ Python
Python Tricks--- Object Comparisons:“is” vs “==”
Python Tricks--- Object Comparisons:“is” vs “==”
119 1
|
存储 索引 Python
Python中的str类型
Python中的str类型
1093 2
|
JSON 安全 数据格式
7-6|python报错TypeError: can't pickle _thread.RLock objects
7-6|python报错TypeError: can't pickle _thread.RLock objects
|
数据处理 Python
【Python】解决tqdm ‘module‘ object is not callable
在使用tqdm库时遇到的“'module' object is not callable”错误,并给出了正确的导入方式以及一些使用tqdm的常见示例。
601 1
|
JSON 数据格式 Python
【python】解决json.dump(字典)时报错Object of type ‘float32‘ is not JSON serializable
在使用json.dump时遇到的“Object of type ‘float32’ is not JSON serializable”错误的方法,通过自定义一个JSON编码器类来处理NumPy类型的数据。
768 1
|
Python
python类型错误(TypeError)
【7月更文挑战第13天】
578 9
|
Python
python类型错误(TypeError)
【7月更文挑战第20天】
457 4
|
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')
178 0

推荐镜像

更多