Python 中常见的 TypeError 是什么?
翻译:BioIT 爱好者
原文:TypeError: A Bytes-Like object Is Required, not 'str' | Finxter
简介
目标:在本教程中,我们的目标是修复以下的 TypeError: A Bytes-Like object Is Required, not 'str' 异常,并且还讨论了类似的异常及其解决方案。
示例:考虑以下文件 'scores.txt',其中包含一些随机候选者的分数。
https://blog.finxter.com/wp-content/uploads/2021/04/scores.txt
Mike - 80
Boby - 60
Joe - 75
Shaw - 85
Ravi - 65

现在,让我们尝试在一个简单程序的帮助下从文件中获得 Ravi 的分数。
with open("scores.txt","rb") as p:
lines = p.readlines()
for line in lines:
string=line.split('-')
if 'Ravi' in string[0]:
print('Marks obtained by Ravi:',string[1].strip())
输出:
Traceback (most recent call last):
File "main.py", line 4, in <module>
string=line.split('-')
TypeError: a bytes-like object is required, not 'str'
解析:
如您所见,我们遇到了一个 TypeError 异常:TypeError: a bytes-like object is required, not 'str',因为我们试图使用 'str' 类型的分隔符分割一个 'bytes' 对象。
因此,要解决我们的问题,首先让我们了解什么是 TypeError?
Python 中的 TypeError 是什么?
TypeError 是 Python 程序员最常面临的问题之一。
每当您在程序中使用不正确或不受支持的对象类型时,都会引发该错误。
如果尝试调用不可调用的对象或通过非迭代标识符进行迭代,也会引发此错误。例如,如果您尝试使用 "str" 添加 "int" 对象。
示例:
a = 1
b = 2
c = 'Three'
print(a + b + c) # Trying to add 'int' objects with 'str'
输出:
Traceback (most recent call last):
File "main.py", line 4, in <module>
print(a + b + c) # Trying to add 'int' objects with 'str'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
解决:
要解决上述问题,可以为变量 c 提供一个 'int' 对象,也可以将变量 a 和 b 的类型转换为 'str' 类型。
TypeError: A Bytes-Like object Is Required, not 'str' 是什么?

当你尝试在仅支持 'bytes' 对象的操作中使用 'str' 对象时,就会引发 TypeError: A Bytes-Like object Is Required, not 'str' 的异常。
因此,你可以看到在上述从 'scores.txt' 中提取数据的示例时,我们尝试使用 'str' 拆分字节对象,这是不受支持的操作。因此,Python 引发 TypeError。
如何修复 TypeError: A Bytes-Like object Is Required, not 'str'?

有许多解决上述异常的方法。您可以使用选择似乎更适合您的程序的方式。让我们一一介绍。
方案1:将 "rb' 替换为 "rt"
你可以简单地将模式从
"rb"(即只读二进制)更改为
"rt"(即只读文本)。你甚至可以使用
'r' 表示只读模式,这是
open() 的默认模式。
with open("scores.txt", "rt") as p: # using rt instead of rb
lines = p.readlines()
for line in lines:
string = line.split('-')
if 'Ravi' in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
输出:
Marks obtained by Ravi: 65
因此,以文本模式打开文件后,你不再需要处理字节对象并轻松使用字符串。
方案2:添加前缀 "b"
你可以在
split()方法中的分隔符之前简单地添加前缀 "b"。此前缀确保您可以处理字节对象。
with open("scores.txt", "rb") as p: # using prefix b
lines = p.readlines()
for line in lines:
string = line.split(b'-')
if b'Ravi' in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
输出:
Marks obtained by Ravi: b'65'
方案3:使用 decode() 方法
decode() 是一种编码方案转换的 Python 方法,在该方案中,将参数字符串编码为另一种所需的编码方案。默认情况下,当未提供编码参数时,decode() 方法会将编码方案设为 "utf-8"。
因此,您可以使用 decode() 方法将 'bytes' 类型的对象解码或转换为 'str' 类型。
with open("scores.txt", "rb") as p:
lines = [x.decode() for x in p.readlines()] # applying decode()
for line in lines:
string = line.split('-') # no exception raised because line is of 'str' type
if 'Ravi' in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
输出:
Marks obtained by Ravi: 65
方案4:使用 encode() 方法
就像
decode() 方法一样,我们可以使用
encode() 方法来解决相同的问题。
with open("scores.txt", "rb") as p:
lines = p.readlines()
for line in lines:
string = line.split('-'.encode()) # encode converts ‘str’ to ‘bytes’
if 'Ravi'.encode() in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
输出:
Marks obtained by Ravi: b'65'
方案5:使用 bytes() 方法
bytes() 是 Python 中的一种方法,可用于将给定的字符串转换为 'bytes' 类型。你需要提供将要转换的源字符串,并将编码(在这种情况下为 "utf-8")作为方法的参数。
让我们应用
bytes() 方法解决我们的问题。
with open("scores.txt", "rb") as p:
lines = p.readlines()
for line in lines:
string = line.split(bytes('-', 'utf-8')) # converts str to bytes
if bytes('Ravi', 'utf-8') in string[0]:
print('Marks obtained by Ravi:', string[1].strip())
输出:
Marks obtained by Ravi: b'65'
注意:UTF-8 是用于编码 Unicode 字符的字节编码。
方案6:使用 List Comprehension 和 str() 方法
解决我们问题的另一种方法是在 list comprehension 中使用
str() 方法。这使您可以将
bytes 对象转换为
str 类型。
with open("scores.txt", "rb") as p:
lines = [str(x) for x in p.readlines()] # using str() to typecast bytes to str
for line in lines:
my_string = line.split('-')
if 'Ravi' in my_string[0]:
print('Marks obtained by Ravi:', my_string[1].strip(" '"))
输出:
Marks obtained by Ravi: 65
总结
现在让我们回顾一下本教程中讨论的关键点:
Python 中的 TypeError 是什么?
TypeError: A Bytes-Like object Is Required, not 'str' 是什么?
如何修复 TypeError: A Bytes-Like object Is Required, not 'str'?
请订阅并继续关注,以便将来进行更多有趣的讨论。
Happy coding!


如何卸载 python setup.py install 安装的包?





本文分享自微信公众号 - 生信科技爱好者(bioitee)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
Python 中常见的 TypeError 是什么?的更多相关文章
- Python中常见的异常总结
Python中常见的异常总结 当Python检测到一个错误时,解释器就会指出当前流已经无法继续执行下去,这时候就出现了异常. 一.异常错误 a.语法错误 错误一: if ...
- python中常见的报错信息
python中常见的报错信息 在运行程序时常会遇到报错提示,报错的信息会提示是哪个方向错的,从而帮助你定位问题: 搜集了一些python最重要的内建异常类名: AttributeError:属性错误, ...
- Python中常见的报错名称
Python中常见的报错名称 1.SyntaxError 语法错误.看看是否用Python关键字命名变量,有没有使用中文符号,运算符.逻辑运算符等符号是不是使用不规范. 2.IndentationEr ...
- Python中常见字符串去除空格的方法总结
Python中常见字符串去除空格的方法总结 1:strip()方法,去除字符串开头或者结尾的空格>>> a = " a b c ">>> a.s ...
- python中常见的错误
python中常见的错误 1.IndentationError: unindent does not match any outer indentation leve 众所周知,Python语法要 ...
- Python 中常见错误总结
IndentationError: unexpected indent Python 中强制缩进,, IndentationError: unexpected indent 缩进错误 这类错误非常常见 ...
- Python中常见的数据类型总结
Python提供多种数据类型来存放数据项集合,主要包括序列(列表list和元组tuple),映射(如字典dict),集合(set),下面对这几种一一介绍: 一 序列 1.列表list 列表是一种有序的 ...
- Python中常见的异常处理
异常和错误 part1:程序中难免出现错误,而错误分成两种 1. 语法错误(这种错误,根本过不了Python解释器的语法检测,必须在程序执行前就改正) # 语法错误示范一 if # 语法错误示范二 d ...
- python中常见的内置函数
map #自定义map函数 def map_test(func, list): res = [] for item in list: res.append(func(item)) return res ...
- python中常见错误及try-except 的用法
1.常见的错误 我们在使用python过程中会出现: (1)SyntaxError 句法错误. (2)IndentationError 缩进错误. (3)NameError 变量未定义错误. (4)T ...
随机推荐
- 这样封装echarts简单好用
为什么要去封装echarts? 在我们的项目中,有很多的地方都使用了echarts图表展示数据. 在有些场景,一个页面有十多个的echarts图. 这些echarts只是展示的指标不一样. 如果我们每 ...
- Clion 连接 WSL 编译Unix环境
Clion 连接 WSL 编译Unix环境 安装 WSL Ubuntu 18版本,创建后不要换源,upgrade后安装CMake.g++.gcc 安装 Clion,创建项目 进入setting 在 B ...
- 微信小程序登录页左上角的home图标如何隐藏?wx.hideHomeButton()不生效?
在做微信小程序时,我们一般都会在app.js中去判断当前用户是否已经登录,如果已经登录,会直接跳转到小程序的首页.如果未登录那么直接跳转登录页. 此时我们需要把首页首页作为微信小程序的pages列表中 ...
- Ajax案例:点击按钮向服务端发送请求,将服务端返回的响应体结果在div中显示(get请求)
客户端代码: <style> #div { width: 200px; height: 100px; border: 2px solid blue; } </style> &l ...
- Cisco RV32X系列路由器 从1day分析到0day挖掘
前言 拿到一个iot设备,笔者比较喜欢先去看一下它的历史漏洞,也许可以从中得到一些启发.发现Cisco之前修补过这个系列设备的命令注入漏洞. https://sec.cloudapps.cisco.c ...
- ORA-17629: Cannot connect to the remote database server
rman远程连接目标库,提示报错ORA-17629: Cannot connect to the remote database server,首先排查网络问题是否通路,结果发现目标端防火墙是开着的, ...
- 手把手逐步解析Javaweb登录实例
一.编写前端界面 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...
- 【LeetCode动态规划#10】完全背包问题实战,其三(单词拆分,涉及集合处理字符串)
单词拆分 力扣题目链接(opens new window) 给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词. 说明: 拆 ...
- java无效发源版本xx
这三个地方统一一下 就可以解决了
- C# 几种获取电脑内存、CPU信息的方案
计数器.WMI 获取设备的内存信息,如系统可用运行内存: 1 public static async Task<double> GetMemoryAvailableAsync(FileSi ...