6
votes

I want to get a list of ints representing the bytes in a string.

3
If you don't mean ASCII values (as you wrote in a comment below), what do you mean? - Tim Pietzcker
Can you give an example of what the string looks like if you are not interested in the ascii values? - Donald Miner
Are you trying to convert string to int - in that case, see my answer - and somebody give me a MindReader badge ;) - Amarghosh
Shall we bet on it (I doubt that's what he wants)? Hey, feature request for meta: Bet rep points on what a question means, winner takes all. - Tim Pietzcker
@Juanjo In that case you can go ahead and remove those down votes; and I must say that you were too fast in down voting the people who came to help you; didn't even wait to clarify your problem! - Amarghosh

3 Answers

12
votes

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]
6
votes

Do you mean the ascii values?

nums = [ord(c) for c in mystring]

or

nums = []
for chr in mystring:
    nums.append(ord(chr))
2
votes

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