如何修复TypeError:不是必需的类似Bytes的对象‘str’?

如何修复TypeError:不需要字节类对象'str'?

◈问题表述

假设您在下面提供了以下文件,并且您想检查某个产品的价格。

Now, you want to check the price for Samsung Galaxy S21 using the following piece of code:

但是,当您执行代码时,会收到以下输出:
输出:

因此,这使我们想到了– 什么是TypeError?是什么导致我们的程序出现此类错误?
Hence, without further delay let us understand the reason behind the occurrence of TypeError and the ways to fix such errors.

◈什么是 TypeError 在 Python?

A TypeError 是 generally raised when a certain operation is applied to an object of an incorrect type.
例子:

输出:

In the above, we tried to add a string object and an integer object using the + operator. This is not allowed and hence we encountered a TypeError.

There can be numerous reasons that lead to the occurrence of TypeError. Some of these reasons are:

  • 尝试在两种类型的对象之间执行不受支持的操作。
  • 尝试呼叫非呼叫者。
  • 尝试迭代非迭代标识符。

Now that we have a clear idea about TypeErrors, let us find out the reason behind the occurrence of TypeError error in our code.

☞‘str’

We opened the file as: 和 open('file_sample.txt', 'rb'). Here rb denotes 二进制模式 which means that all the data being read from the file is returned as 个字节. Hence, when you look at line 6, you will find that we are trying to split a byte object using a string. This operation is not allowed and leads to to a TypeError.

那么,我们如何解决程序中的此错误?🤔 Let’深入研究解决问题的方法!

方法1:转换为字节对象

The easiest solution to our problem is to ensure that the object types match by converting the delimiter string within the 分裂() function to a byte object. You can achieve this by using the prefix b before the delimiter string within the 分裂() function. This allows you to operate upon a 字节对象 within the 分裂() function, thereby avoiding the TypeError.

解决方案:

输出:

✨ Method 2: Using 解码()

在我们的代码中,我们试图以二进制模式读取文件,然后创建一个字节列表。在for循环中,我们正在比较 力量ing个字节 and that is exactly where the code is failing. So to overcome this, you can decode the bytes while adding them to the list using the 解码() function.

❖ The 解码() method allows you to convert from one encoding scheme, in which the argument string is encoded to another desired encoding scheme. 

Let us have a look at the following code to understand how we can fix the TypeError 在 our code.

输出:

✨ Method 3: Using 编码()

❖ The 编码() method in Python is used to encode the string, using the specified encoding.

Therefore, you can encode the delimiter string within the 分裂() function using .encode() and then proceed with the next steps in your program as shown below.

输出:

✨方法4:在文本模式下打开文件

解决我们问题的另一种方法是在 文字模式. You can achieve this by using rt instead of rb inside the 打开() function.

解决方案:

输出:

结论

在本文中,我们了解到:

  • What is TypeError?
  • Reasons behind TypeError?
  • 如何修复TypeError:不需要字节类对象‘str’?
    • 方法1:通过将类型转换为Byte类型对象。
    • Method 2: Using 编码() function.
    • Method 3: Using 解码() function.
    • 方法4:在文本模式下打开文件。

到此为止,我们到了本文的结尾,希望您学习愉快!请 订阅 敬请期待,以后还会有更多有趣的文章和讨论。祝您学习愉快!📚

相关文章

发表评论

您的电子邮件地址不会被公开。 必需的地方已做标记 *

订阅我们的新闻

获取质量教程到您的收件箱。现在订阅。