Python程式將位元組字串轉換為列表
位元組字串類似於字串(Unicode),但它包含一系列位元組而不是字元。處理純ASCII文字而不是Unicode文字的應用程式可以使用位元組字串。
在Python中將位元組字串轉換為列表提供了相容性、可修改性和更容易訪問單個位元組的功能。它允許與其他資料結構無縫整合,方便修改元素,並能夠有效地分析和操作位元組字串的特定部分。
演示
假設我們已經獲取了一個輸入位元組字串。我們現在將使用上述方法將給定的位元組字串轉換為ASCII值的列表,如下所示。
輸入
inputByteString = b'Tutorialspoint'
輸出
List of ASCII values of an input byte string: [84, 117, 116, 111, 114, 105, 97, 108, 115, 112, 111, 105, 110, 116]
使用的方法
以下是完成此任務的各種方法
使用list()函式
使用for迴圈和ord()函式
使用from_bytes()函式
方法1:使用list()函式
此方法將演示如何使用Python的簡單list()函式將位元組字串轉換為列表字串。
list()函式
返回可迭代物件的列表。這意味著它將可迭代物件轉換為列表。
語法
list([iterable])
演算法(步驟)
以下是執行所需任務應遵循的演算法/步驟。
建立一個變數來儲存輸入位元組字串。
使用list()函式將輸入位元組字串轉換為包含輸入位元組的ASCII值的列表,並將輸入位元組字串作為引數傳遞,並列印結果列表。
示例
以下程式使用list()函式將輸入位元組字串轉換為列表,並返回輸入位元組字串的ASCII值的列表。
# input byte string inputByteStr = b'Tutorialspoint' # converting the input byte string into a list # which contains the ASCII values as a list of an input byte string print("List of ASCII values of an input byte string:") print(list(inputByteStr))
輸出
執行上述程式後,將生成以下輸出
List of ASCII values of an input byte string: [84, 117, 116, 111, 114, 105, 97, 108, 115, 112, 111, 105, 110, 116]
方法2:使用for迴圈和ord()函式
在此方法中,我們將使用Python的簡單for迴圈和ord()函式的組合來將給定的位元組字串轉換為列表。
ord()函式
將給定字元的Unicode程式碼作為數字返回。
語法
ord(char)
引數
char: 輸入位元組字串。
演算法(步驟)
以下是執行所需任務應遵循的演算法/步驟
建立一個變數來儲存輸入位元組字串。
建立一個空列表來儲存輸入位元組字串字元的ASCII值。
使用for迴圈遍歷輸入位元組字串的每個字元。
使用ord()函式(將給定字元的Unicode程式碼/ASCII值作為數字返回)獲取每個字元的ASCII值。
使用append()函式(在末尾將元素新增到列表中)將其追加到結果列表中。
列印輸入位元組字串的Unicode/ASCII值,即將其轉換為列表。
示例
以下程式使用for迴圈和ord()函式將輸入位元組字串轉換為列表,並返回輸入位元組字串的ASCII值的列表。
# input byte string inputByteStr = 'Tutorialspoint' # empty list for storing the ASCII values of input byte string characters resultantList = [] # traversing through each character of the input byte string for c in inputByteStr: # getting the ASCII value of each character using the ord() function # and appending it to the resultant list resultantList.append(ord(c)) # Printing the Unicode/ASCII values of an input byte string print("List of ASCII values of an input byte string:", resultantList)
輸出
執行上述程式後,將生成以下輸出
List of ASCII values of an input byte string: [84, 117, 116, 111, 114, 105, 97, 108, 115, 112, 111, 105, 110, 116]
方法3:使用from_bytes()函式
在此方法中,我們將瞭解如何使用from_bytes()函式將位元組字串轉換為列表。
from_bytes()函式
要將給定的位元組字串轉換為等效的int值,請使用from_bytes()函式。
語法
int.from_bytes(bytes, byteorder, *, signed=False)
引數
bytes: 位元組物件。
byteorder: 整數值的表示順序。在“小端”位元組序中,最高有效位儲存在末尾,最低有效位儲存在開頭,而在“大端”位元組序中,MSB放在開頭,LSB放在末尾。大端位元組序確定整數的256進位制值。
signed: 其預設值為False。此引數指示是否表示數字的二進位制補碼。
示例
以下程式使用from_bytes()函式將給定的輸入位元組字串轉換為列表
# input byte string inputByteStr = b'\x00\x01\x002' # Converting the given byte string to int # Here big represents the byte code intValue = int.from_bytes(inputByteStr , "big") # Printing the integer value of an input byte string print(intValue)
輸出
65586
結論
本文向我們介紹了三種將給定位元組字串轉換為列表的不同方法。此外,我們還學習瞭如何使用ord()函式獲取字元的ASCII值。最後,我們學習瞭如何使用append()函式在末尾將元素新增到列表中。