如何在Python中将字符串转换为字节数组

如何在Python中将字符串转换为字节数组

问题描述:

假设我有一个 4 个字符的字符串,我想将此字符串转换为一个字节数组,其中字符串中的每个字符都被转换为其等效的十六进制.例如

Say that I have a 4 character string, and I want to convert this string into a byte array where each character in the string is translated into its hex equivalent. e.g.

str = "ABCD"

我试图让我的输出成为

I'm trying to get my output to be

array('B', [41, 42, 43, 44])

有没有直接的方法来实现这一点?

Is there a straightforward way to accomplish this?

encode 函数可以帮到你,encode 返回一个编码后的字符串

encode function can help you here, encode returns an encoded version of the string

In [44]: str = "ABCD"

In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']

或者你可以使用数组模块

or you can use array module

In [49]: import array

In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])