Is there any neat trick to slice a binary number into groups of five digits in python?
\'00010100011011101101110100010111\' => [\'00010\', \'00110\', \'10111\', ... ]
My question was duplicated by this one, so I would answer it here.
I got a more general and memory efficient answer for all this kinds of questions using Generators
from itertools import islice
def slice_generator(an_iter, num):
an_iter = iter(an_iter)
while True:
result = tuple(islice(an_iter, num))
if not result:
return
yield result
So for this question, We can do:
>>> l = '00010100011011101101110100010111'
>>> [''.join(x) for x in slice_generator(l,5)]
['00010', '10001', '10111', '01101', '11010', '00101', '11']