在 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