I have a string with digits like so – digit = "7316717"
Now I want to split the string in such a way that the output is a moving window of 3 digits at a time. So I get –
["731", "316", "167", "671", "717"]
How would the approach be? Straightforward way is to put in for-loop and iterate. But I feel some inbuilt python string function can do this in less code. Know of any such approach?
Advertisement
Answer
The itertools examples provides the window
function that does just that:
JavaScript
x
12
12
1
from itertools import islice
2
def window(seq, n=2):
3
"Returns a sliding window (of width n) over data from the iterable"
4
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
5
it = iter(seq)
6
result = tuple(islice(it, n))
7
if len(result) == n:
8
yield result
9
for elem in it:
10
result = result[1:] + (elem,)
11
yield result
12
Example usage:
JavaScript
1
3
1
>>> ["".join(x) for x in window("7316717", 3)]
2
['731', '316', '167', '671', '717']
3