Split a string into unevenly sized chunks in a repeating pattern
<p>I have a string representing a series of bits:</p>

<pre><code>bit_stream = "10100101011101011101011"  # ...(so on)
</code></pre>

<p>I need to split this into unevenly sized chunks in a repeating pattern. The first chunk should be length 1, followed by a chunk of length 8, then a chunk of length 2, and so on until the bits are exhausted:</p>

<pre><code>result = ["1", "01001010", "11", "1", "01011101", "01", "1"]  # ...(so on)
</code></pre>

<p>One way is to use a class to track state and an iterator to return groups of bits.  <code>itertools.cycle</code> is used to generate the bit counts repeatedly:</p>

<pre><code>from itertools import cycle

class Bits(object):

    def __init__(self,input_bits,bit_counts):
        self.bits = input_bits
        self.counts = cycle(bit_counts)

    def __iter__(self):
        while self.bits:
            count = next(self.counts)
            bits,self.bits = self.bits[:count],self.bits[count:]
            yield bits

print(list(Bits('10100101011101011101011',(1,8,2))))
</code></pre>

<p>Output:</p>

<pre><code>['1', '01001010', '11', '1', '01011101', '01', '1']
</code></pre>

python python-2.7 split