Let's say I have abcdefgh. I want all the sequential substrings of length k. So for this string if k = 4, I would want abcd bcde cdef defg efgh. I would just loop through with the indices, but is there a more "pythonic" way?
How about:
In [13]: s = "abcdefgh"
In [14]: [s[i:i+4] for i in xrange(len(s)-3)]
Out[14]: ['abcd', 'bcde', 'cdef', 'defg', 'efgh']
Still a loop, but wrapped in a list comprehension.
Or, if you want to get fancy:
In [18]: map(''.join, zip(*(s[i:] for i in range(4))))
Out[18]: ['abcd', 'bcde', 'cdef', 'defg', 'efgh']
(Personally, I wouldn't use the latter as it's rather obtuse.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With