4

If i have this string:

"0110100001100101011011000110110001101111"

How can I divide it at every eighth character into smaller strings, and put it into a list, so that it looks like this?:

['01101000','01100101','01101100','01101100','01101111']

So far, I can't figure out how this would be possible.

I should mention, since my strings are in binary so the length is always a multiple of 8.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Peaser
  • 565
  • 3
  • 8
  • 16
  • You can easily modify the answers given on the duplicate to handle strings instead. – jonrsharpe Jun 17 '14 at 15:30
  • @jonrsharpe I don't think the answers for that other question contain the most elegant way to solve the specific problem at hand. How easily adjustable those answers are depends on the python-experience of the OP. – timgeb Jun 17 '14 at 15:41
  • @timgeb [This question](http://stackoverflow.com/q/9475241/3001761) is arguably closer, but is also closed as a duplicate! – jonrsharpe Jun 17 '14 at 15:42
  • @jonrsharpe ah yes, that would indeed be a better fit! – timgeb Jun 17 '14 at 15:44
  • @timgeb I didn't realise you could close as duplicate of a duplicate! – jonrsharpe Jun 17 '14 at 15:47
  • @jonrsharpe oh, you can? I wouldn't know. In case you were being sarcastic, I just would not have closed that other duplicate question as a duplicate to begin with. :) – timgeb Jun 17 '14 at 15:49

3 Answers3

8
>>> mystr = "0110100001100101011011000110110001101111"
>>> [mystr[i:i+8] for i in range(0, len(mystr), 8)]
['01101000', '01100101', '01101100', '01101100', '01101111']

The solution uses a so called list comprehension (this seems to be a pretty decent tutorial) and is doing basically the same as Aleph's answer, just in one line.

timgeb
  • 76,762
  • 20
  • 123
  • 145
3
t=[]
for i in range(len(yourstring)/8):
    t.append(yourstring[i*8: (i+1)*8])
Aleph
  • 199
  • 2
  • 13
3

You can also use re

import re

In [21]: s="0110100001100101011011000110110001101111"

In [22]: re.findall('.{8}',s)
Out[22]: ['01101000', '01100101', '01101100', '01101100', '01101111']

As your strings only contain digits we can use . to match any character.

You can also explicitly use the \d{8} which matches 8 digits in a low.

In [23]: In [22]: re.findall('\d{8}',s)
Out[23]: ['01101000', '01100101', '01101100', '01101100', '01101111']
jrjc
  • 21,103
  • 9
  • 64
  • 78
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321