如何在Python中将字符串转换为字节数组 [英] How to convert string to byte array in 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])
这篇关于如何在Python中将字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文