How to convert string to byte array in Python
Solution 1:
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])
Solution 2:
Just use a bytearray()
which is a list of bytes.
Python2:
s = "ABCD"
b = bytearray()
b.extend(s)
Python3:
s = "ABCD"
b = bytearray()
b.extend(map(ord, s))
By the way, don't use str
as a variable name since that is builtin.