什麼是 Python 位元組串?
Python 位元組串是位元組序列。在 Python 3 中,位元組串使用“bytes”資料型別表示。位元組串用於表示不適合 Unicode 字元集的二進位制資料,例如影像、音訊和影片檔案。
以下是一些演示如何使用 Python 位元組串的程式碼示例
建立位元組串
要在 Python 中建立位元組串,我們可以在字串字面量之前使用“b”字首。
示例
在此示例中,我們建立了一個內容為“This is a bytestring.”的位元組串,並將其分配給變數“bytestring”。然後我們將位元組串列印到控制檯。“b”字首在字串字面量之前告訴 Python 將字串解釋為位元組串。
bytestring = b"This is a bytestring." print(bytestring)
輸出
b'This is a bytestring.'
將字串轉換為位元組串
我們可以使用“encode()”方法將普通字串轉換為位元組串。
示例
在此示例中,我們有一個內容為“This is a string.”的普通字串,我們希望將其轉換為位元組串。我們使用“encode()”方法將字串轉換為位元組串,並將其分配給變數“bytestring”。然後我們將位元組串列印到控制檯。
string = "This is a string." bytestring = string.encode() print(bytestring)
輸出
b'This is a string.'
將位元組串轉換為字串
我們可以使用“decode()”方法將位元組串轉換為普通字串。
示例
在此示例中,我們有一個內容為“This is a bytestring.”的位元組串,我們希望將其轉換為普通字串。我們使用“decode()”方法將位元組串轉換為字串,並將其分配給變數“string”。然後我們將字串列印到控制檯。
bytestring = b"This is a bytestring." string = bytestring.decode() print(string)
輸出
This is a bytestring.
使用位元組串方法
位元組串有許多與普通字串類似的方法。這是一個使用“startswith()”方法與位元組串的示例
示例
bytestring = b"This is a bytestring."
if bytestring.startswith(b"This"):
print("The bytestring starts with 'This'")
else:
print("The bytestring doesn't start with 'This'")
輸出
The bytestring starts with 'This'
將位元組串寫入和讀取到檔案
我們可以使用“wb”模式將位元組串寫入檔案,並使用“rb”模式將其讀回。
示例
在此示例中,我們首先使用“wb”模式將位元組串寫入名為“bytestring.txt”的檔案。然後我們使用“rb”模式再次開啟檔案,並將內容讀回一個名為“read_bytestring”的變數中。然後我們將位元組串列印到控制檯。
bytestring = b"This is a bytestring."
with open("bytestring.txt", "wb") as file:
file.write(bytestring)
with open("bytestring.txt", "rb") as file:
read_bytestring = file.read()
print(read_bytestring)
輸出
b'This is a bytestring.'
連線位元組串
我們可以使用“+”運算子連線位元組串。這是一個示例
示例
在此示例中,我們有兩個位元組串,我們希望將它們連線起來。我們使用“+”運算子連線位元組串,並將結果分配給一個名為“concatenated_bytestring”的新變數。然後我們將連線後的位元組串列印到控制檯。
bytestring1 = b"This is the first bytestring. " bytestring2 = b"This is the second bytestring." concatenated_bytestring = bytestring1 + bytestring2 print(concatenated_bytestring)
輸出
b'This is the first bytestring. This is the second bytestring.'
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP