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:

三种转换方式:

以上,问题解决~

相关文章
|
开发者 Python
【Python】已解决:TypeError: __init__() got an unexpected keyword argument ‘port’
【Python】已解决:TypeError: __init__() got an unexpected keyword argument ‘port’
2975 0
【Python】已解决:TypeError: __init__() got an unexpected keyword argument ‘port’
|
Python
python类型错误(TypeError)
【7月更文挑战第13天】
824 9
|
Python
python类型错误(TypeError)
【7月更文挑战第20天】
682 4
|
并行计算 Serverless API
函数计算操作报错合集之出现 "AttributeError: 'NoneType' object has no attribute 'pop'" 错误,是什么原因
在使用函数计算服务(如阿里云函数计算)时,用户可能会遇到多种错误场景。以下是一些常见的操作报错及其可能的原因和解决方法,包括但不限于:1. 函数部署失败、2. 函数执行超时、3. 资源不足错误、4. 权限与访问错误、5. 依赖问题、6. 网络配置错误、7. 触发器配置错误、8. 日志与监控问题。
677 1
|
JSON 安全 数据格式
7-6|python报错TypeError: can't pickle _thread.RLock objects
7-6|python报错TypeError: can't pickle _thread.RLock objects
|
Ubuntu
Ubuntu22.04,AOSP编译报错: libncurses.so.5: cannot open shared object file: No such file
本文描述了在Ubuntu 22.04系统上编译AOSP时遇到的`libncurses.so.5`缺失错误,并提供了通过安装相应库解决该问题的步骤。
3007 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’
325 0
|
Web App开发 测试技术 API
【Python】已解决:TypeError: *init*() got an unexpected keyword argument ‘firefox_options’
【Python】已解决:TypeError: *init*() got an unexpected keyword argument ‘firefox_options’
461 0
|
Python
【Python】已解决:(Python xlwt写入Excel报错)AttributeError: ‘function’ object has no attribute ‘font’
【Python】已解决:(Python xlwt写入Excel报错)AttributeError: ‘function’ object has no attribute ‘font’
354 0
|
Python
【Python】已解决:(Python写入Excel表格报错)‘NoneType’ object has no attribute ‘write’
【Python】已解决:(Python写入Excel表格报错)‘NoneType’ object has no attribute ‘write’
1343 0

推荐镜像

更多