tags:

views:

78

answers:

3

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

+3  A: 

Do you mean the ascii values?

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

or

nums = []
for chr in mystring:
    nums.append(ord(chr))
orangeoctopus
Why the downvote?
Tim Pietzcker
I don't see why this is downvoted...
Justin Ardini
I was wondering the same... thanks for the +1s guys.
orangeoctopus
Yeah, it's the least we could do :)
Tim Pietzcker
I even deleted my answer seeing yours as this is the better one and put a comment (hence deleted) saying -1 for not using simpler method - then I saw the down vote and the comment... Undeleted to see what he is looking for.
Amarghosh
+5  A: 

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]
Scott Griffiths
To clarify for the OP, these values *are* the ascii values.
Justin Ardini
+2  A: 

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

Daan
@Amarghosh: That's kind of what I'm betting on here :).Not that the input would be a string of zeroes and ones, but actual real binary data that happens to represent some integers. I learned this when I tried to solve Vortex0, which I suspect the question poster is trying to solve.. (http://www.overthewire.org/wargames/vortex/level0.shtml)Apologies for commenting here, I seem to be unable to comment on the actual question. (I'm new here!)
Daan
Clever guess, +1. By now the author has explained what he really did want, but anyway...
Tim Pietzcker
You need 50 rep to comment on other peoples posts - I just made you 10 points closer.
Amarghosh
Thank you both.All this commotion over a problem that was already solved :)
Daan
@Daan Welcome to SO ;)
Amarghosh