Here's how I would do it:
>>> s = "The quick brown fox jumps over the lazy dog"
>>> l = [1, 8, 14, 18, 27]
>>> l = [0] + l + [len(s)]
>>> [s[x:y] for x,y in zip(l, l[1:])]
['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog']
Some explanation:
I'am adding 0 to the front and len(s)
to the end of the list, such that
>>> zip(l, l[1:])
[(0, 1), (1, 8), (8, 14), (14, 18), (18, 27), (27, 43)]
gives me a sequence of tuples of slice indices. All that's left to do is unpack those indices in a list comprehension and generate the slices you want.
edit:
If you really care about the memory footprint of this operation, because you deal with very large large strings and lists often of times, use generators all the way and build your list l
such that it includes the 0 and len(s)
in the first place.
For Python 2:
>>> from itertools import izip, tee
>>> s = "The quick brown fox jumps over the lazy dog"
>>> l = [0, 1, 8, 14, 18, 27, 43]
>>>
>>> def get_slices(s, l):
... it1, it2 = tee(l)
... next(it2)
... for start, end in izip(it1, it2):
... yield s[start:end]
...
>>> list(get_slices(s,l))
['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog']
For Python 3:
zip
does what izip
did in Python 2 (see Python 3.3 version)
For Python 3.3+ with the yield from
syntax:
>>> from itertools import tee
>>> s = "The quick brown fox jumps over the lazy dog"
>>> l = [0, 1, 8, 14, 18, 27, 43]
>>>
>>> def get_slices(s, l):
... it1, it2 = tee(l)
... next(it2)
... yield from (s[start:end] for start, end in zip(it1, it2))
...
>>> list(get_slices(s,l))
['T', 'he quic', 'k brow', 'n fo', 'x jumps o', 'ver the lazy dog']