Reputation: 30023
I want to get a list of ints representing the bytes in a string.
Upvotes: 9
Views: 15032
Reputation: 76
Perhaps you mean a string of bytes, for example received over the net, representing a couple of integer values?
In that case you can "unpack" the string into the integer values by using unpack() and specifying "i" for integer as the format string.
See: http://docs.python.org/library/struct.html
Upvotes: 2
Reputation: 21925
One option for Python 2.6 and later is to use a bytearray
:
>>> b = bytearray('hello')
>>> b[0]
104
>>> b[1]
101
>>> list(b)
[104, 101, 108, 108, 111]
For Python 3.x you'd need a bytes
object rather than a string in any case and so could just do this:
>>> b = b'hello'
>>> list(b)
[104, 101, 108, 108, 111]
Upvotes: 14
Reputation: 39893
Do you mean the ascii values?
nums = [ord(c) for c in mystring]
or
nums = []
for chr in mystring:
nums.append(ord(chr))
Upvotes: 7