:
1 , , - str.split. 2 , , pairwise itertools:
http://docs.python.org/library/itertools.html#recipes
, n- :
import itertools
def nwise(iterable, n):
"""nwise(iter([1,2,3,4,5]), 3) -> (1,2,3), (2,3,4), (4,5,6)"""
iterables = itertools.tee(iterable, n)
slices = (itertools.islice(it, idx, None) for (idx, it) in enumerate(iterables))
return itertools.izip(*slices)
And we get a simple and modular code:
>>> s = "The quick, brown fox jumps over the lazy dog."
>>> list(nwise(s.split(), 3))
[('The', 'quick,', 'brown'), ('quick,', 'brown', 'fox'), ('brown', 'fox', 'jumps'), ('fox', 'jumps', 'over'), ('jumps', 'over', 'the'), ('over', 'the', 'lazy'), ('the', 'lazy', 'dog.')]
Or as you requested:
>>>
>>> [" ".join(words) for words in nwise(s.split(), 3)]
['The quick, brown', 'quick, brown fox', 'brown fox jumps', 'fox jumps over', 'jumps over the', 'over the lazy', 'the lazy dog.']