在 Python 中将 Bytearray 转换为字符串

  1. 使用 Python 中的 bytes() 函数将 bytearray 转换为字符串
  2. 使用 Python 中的 bytearray.decode() 函数将 bytearray 转换为字符串
在 Python 中将 Bytearray 转换为字符串

你可以使用两种主要方法将 bytearray 转换为 Python 中的字符串: bytes()bytearray.decode()。在本教程中,我们将向你展示如何将这些函数用作这种特殊转换的方法。

使用 Python 中的 bytes() 函数将 bytearray 转换为字符串

如果我们有一个 bytearray 包含带有 utf-8 编码的字符串字符,并且想要将该数组转换为字符串变量,我们可以使用 Python 中的内置 bytes() 函数。

bytes() 函数返回一个不可变的字节对象,然后可以将其存储在字符串变量中。以下代码片段演示了如何使用 bytes() 函数将 bytearray 转换为字符串。

b = bytearray("test", encoding="utf-8")
str1 = bytes(b)
print(str1)

输出:

b'test'

我们使用上面代码中的 bytes() 函数将 bytearray 对象 b 转换为字符串变量 str1。首先,我们在 bytearray 对象内使用 utf-8 编码对文本 test 进行编码。然后我们使用 bytes() 函数将 bytearray 转换为字符串,并将结果存储在字符串变量 str1 中。

最后,我们将数据打印在 str1 变量中。输出显示此过程在原始数据的开头添加了一个 b 对象,然后将数据括在单引号中。这个问题在接下来讨论的方法中得到解决。

使用 Python 中的 bytearray.decode() 函数将 bytearray 转换为字符串

正如我们所见,bytes() 函数将 bytearray 转换为字符串,但会向原始字符串添加额外的数据。这个问题可以通过字符串操作来解决,但过程繁琐。bytearray.decode() 函数 自动为我们做这件事。此方法解码最初在 bytearray 中编码的数据。

以下代码片段演示了如何使用 bytearray.decode() 函数将 bytearray 转换为字符串。

b = bytearray("test", encoding="utf-8")
str1 = b.decode()
print(str1)

输出:

test

我们使用上面代码中的 b.decode() 函数将 bytearray 对象 b 转换为字符串变量 str1。首先,我们在 bytearray 对象内使用 utf-8 编码对文本 test 进行编码。然后我们使用 b.decode() 函数将 bytearray 转换为字符串,并将结果存储在字符串变量 str1 中。最后,我们将数据打印在 str1 变量中。输出显示这个过程不会向我们最初编码的数据添加任何额外的数据。

从上面的演示可以看出,bytearray.decode() 方法在将 bytearray 对象转换为 string 变量方面明显优于 byte() 方法。

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相关文章 - Python String