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()函数
在这种方法中,我们将使用简单的for循环和Python的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: 这是整数值的表示顺序。在“little”字节顺序中,最高有效位存储在末尾,最低有效位存储在开头;而在“big”字节顺序中,最高有效位放置在开头,最低有效位放置在末尾。大字节顺序确定了一个整数的基于256的值。
-
signed: 默认值为False。该参数指示是否表示一个数字的2的补码。
示例
以下程序使用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()函数在列表末尾添加元素。