3

I have very long binary numbers stored in strings. Each 8 characters (i.e. each 8-bit chunk) represent an ASCII character code. To give an example, 0100100001101001 is 2 8-bit numbers (01001000 & 01101001), which are the character codes for 'H' & 'i'. So the whole thing is a binary representation of 'Hi'.

My question is, is there a way to force a for loop iterate through a string in bigger chunks so that I can read 8 letters at a time? In other words, I'd like the for loop to assign 8 characters to my iterator variable per loop iteration instead of 1, so that I can easily determine the character codes represented by the string.

Thanks in advance.

  • Not a duplicate: this one is about strings, the other one is about "general" kinds of lists. `textwrap` will probably only work on strings. – glglgl Jan 21 '14 at 13:40

1 Answers1

5

Just throwing this answer in, perhaps not the most appropriate way to do things, but you can use textwrap:

>>> import textwrap
>>> s = '0100100001101001'
>>> textwrap.wrap(s, 8)
['01001000', '01101001']
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • That's a decent solution. Taking it one step further, after reading about that function, the code: `code` b=textwrap.wrap(s, 8) `code` creates a new list that is easily iterable. Thanks – user2702924 Jan 21 '14 at 11:37
  • It made me wait a couple minutes before I could accept it :) – user2702924 Jan 21 '14 at 11:45
  • 2
    I am missing a warning here about things that the function does without the user possibly aware of: `expand_tabs`, `replace_whitespace`, etc. – glglgl Jan 21 '14 at 13:43