Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to take sequential substrings python

Tags:

python

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?

like image 782
goodcow Avatar asked Jun 16 '26 05:06

goodcow


1 Answers

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.)

like image 94
NPE Avatar answered Jun 18 '26 20:06

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!