凯发真人娱乐

python 中常见的 typeerror 是什么? -凯发真人娱乐

2023-08-17,,

翻译:bioit 爱好者
原文:: 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 
    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 
    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 列表、字典、元组的一些小技巧

2021-03-30

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

2020-05-15

生物信息学 python 入门之源码安装

2019-09-29

python 日期和时间函数使用指南

2019-09-21

python 文件与目录操作方法总结

2019-02-17

本文分享自微信公众号 - 生信科技爱好者(bioitee)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“osc源创计划”,欢迎正在阅读的你也加入,一起分享。

python 中的 typeerror 是什么?的相关教程结束。

网站地图