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
2010-07-15 13:38:11
Why the downvote?
Tim Pietzcker
2010-07-15 13:47:40
I don't see why this is downvoted...
Justin Ardini
2010-07-15 13:48:04
I was wondering the same... thanks for the +1s guys.
orangeoctopus
2010-07-15 13:49:18
Yeah, it's the least we could do :)
Tim Pietzcker
2010-07-15 13:50:10
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
2010-07-15 14:01:03
+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
2010-07-15 13:40:54
+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.
Daan
2010-07-15 13:59:57
@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
2010-07-15 14:18:33
Clever guess, +1. By now the author has explained what he really did want, but anyway...
Tim Pietzcker
2010-07-15 14:27:14
You need 50 rep to comment on other peoples posts - I just made you 10 points closer.
Amarghosh
2010-07-15 14:30:54
Thank you both.All this commotion over a problem that was already solved :)
Daan
2010-07-15 14:33:23