susdu susdu - 1 month ago 8
Python Question

pythonic way to split string into variable length chunks?

For example, string

0123456789

with input
1,2,6,1
would be:

[0,12,345678,9]

Answer

One way to do this, is with itertools.islice:

from itertools import islice

chunks = (1,2,6,1)
s = '0123456789'
assert len(s) >= sum(chunks)

it = iter(s)
result = [int(''.join(islice(it, i))) for i in chunks]
print(result)
# [0, 12, 345678, 9]
Comments