在 Python 中将 ASCII 代码列表转换为字符串(字节数组)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3470398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:13:35  来源:igfitidea点击:

Convert list of ASCII codes to string (byte array) in Python

python

提问by mikewaters

I have a list of integer ASCII values that I need to transform into a string (binary) to use as the key for a crypto operation. (I am re-implementing java crypto code in python)

我有一个整数 ASCII 值列表,我需要将其转换为字符串(二进制)以用作加密操作的密钥。(我正在python中重新实现java加密代码)

This works (assuming an 8-byte key):

这有效(假设一个 8 字节的密钥):

key = struct.pack('BBBBBBBB', 17, 24, 121, 1, 12, 222, 34, 76)

However, I would prefer to not have the key length and unpack() parameter list hardcoded.

但是,我希望不要对密钥长度和 unpack() 参数列表进行硬编码。

How might I implement this correctly, given an initial list of integers?

给定初始整数列表,我该如何正确实现?

Thanks!

谢谢!

采纳答案by Alex Martelli

I much prefer the arraymodule to the structmodule for this kind of tasks (ones involving sequences of homogeneousvalues):

对于此类任务(涉及同质值序列的任务),我更喜欢array模块而不是struct模块:

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'

no lencall, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!

不需要len调用,不需要字符串操作等——快速、简单、直接,为什么更喜欢其他方法?!

回答by Katriel

key = "".join( chr( val ) for val in myList )

回答by Katriel

struct.pack('B' * len(integers), *integers)

*sequencemeans "unpack sequence" - or rather, "when calling f(..., *args ,...), let args = sequence".

*sequence意思是“解包序列” - 或者更确切地说,“调用时f(..., *args ,...),让args = sequence”。

回答by Scott Griffiths

For Python 2.6 and later if you are dealing with bytes then a bytearrayis the most obvious choice:

对于 Python 2.6 及更高版本,如果您正在处理字节,那么 abytearray是最明显的选择:

>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'

To me this is even more direct than Alex Martelli's answer - still no string manipulation or lencall but now you don't even need to import anything!

对我来说,这比 Alex Martelli 的回答更直接——仍然没有字符串操作或len调用,但现在你甚至不需要导入任何东西!

回答by Pi Delport

This is reviving an old question, but in Python 3, you can just use bytesdirectly:

这是一个老问题,但在 Python 3 中,您可以直接使用bytes

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

回答by Denis Shatov

Shorter version of previous using map()function (works for python 2.7):

先前 usingmap()函数的较短版本(适用于 python 2.7):

"".join(map(chr, myList))

"".join(map(chr, myList))