Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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)

This works (assuming an 8-byte key):

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.

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

Thanks!

like image 957
mikewaters Avatar asked Aug 12 '10 17:08

mikewaters


People also ask

How do I convert ASCII to text in Python?

chr () is a built-in function in Python that is used to convert the ASCII code into its corresponding character. The parameter passed in the function is a numeric, integer type value. The function returns a character for which the parameter is the ASCII code.

How do I turn a list into a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


3 Answers

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

>>> 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 len call but now you don't even need to import anything!

like image 76
Scott Griffiths Avatar answered Oct 24 '22 12:10

Scott Griffiths


I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):

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

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

like image 25
Alex Martelli Avatar answered Oct 24 '22 12:10

Alex Martelli


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

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'
like image 48
Pi Delport Avatar answered Oct 24 '22 11:10

Pi Delport