Python split string in moving window

The itertools examples provides the window function that does just that:

from itertools import islice
def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result    
    for elem in it:
        result = result[1:] + (elem,)
        yield result

Example usage:

>>> ["".join(x) for x in window("7316717", 3)]
['731', '316', '167', '671', '717']

Leave a Comment