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>I did this similarly to the other answer posted about a minute ago but I didn't use a class to track state.</p>

<pre><code>import itertools

def alternating_size_chunks(iterable, steps):
    n = 0
    step = itertools.cycle(steps)
    while n &lt; len(iterable):
        next_step = next(step)
        yield iterable[n:n + next_step]
        n += next_step
</code></pre>

<p>Testing:</p>

<pre><code>&gt;&gt;&gt; test_string = ''.join(random.choice('01') for _ in range(50))
&gt;&gt;&gt; print(list(alternating_size_chunks(test_string, (1, 8, 2))))
['1', '01111010', '01', '1', '00111011', '11', '0', '11010100', '01', '0', '10011101', '00', '0', '11111']
</code></pre>

<p>Note that both these methods (mine and Mark's answer) will take an arbitrary set of lengths (whether it's 1, 8, 2 or anything else), and will work even if the length of the bit stream doesn't precisely add up to a multiple of the sum of the lengths. (You can see in my example it ran out of bits and the last chunk only has five.) This may or may not be desirable in your case, so you might want to check that you have enough data to convert once you get ready to do that.</p>

<p>Reference: <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle" rel="nofollow"><code>itertools.cycle</code></a></p>

python python-2.7 split