This is turning out to be trickier than I expected. I have a byte string:
data = b\'abcdefghijklmnopqrstuvwxyz\'
I want to read this data in c
Funcy (a library offering various useful utilities, supporting both Python 2 and 3) offers a chunks function that does exactly this:
>>> import funcy
>>> data = b'abcdefghijklmnopqrstuvwxyz'
>>> list(funcy.chunks(6, data))
[b'abcdef', b'ghijkl', b'mnopqr', b'stuvwx', b'yz'] # Python 3
['abcdef', 'ghijkl', 'mnopqr', 'stuvwx', 'yz'] # Python 2.7
Alternatively, you could include a simple implementation of this in your program (compatible with both Python 2.7 and 3):
def chunked(size, source):
for i in range(0, len(source), size):
yield source[i:i+size]
It behaves the same (at least for your data; Funcy's chunks
also works with iterators, this doesn't):
>>> list(chunked(6, data))
[b'abcdef', b'ghijkl', b'mnopqr', b'stuvwx', b'yz'] # Python 3
['abcdef', 'ghijkl', 'mnopqr', 'stuvwx', 'yz'] # Python 2.7