3

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?

4
  • 2
    Do you want efficient, or Pythonic? Python values obviousness and readability over efficiency (because coder efficiency > program efficiency in Python's world). Commented Mar 3, 2014 at 20:36
  • Hm, efficient would be good Commented Mar 3, 2014 at 20:38
  • 2
    How are you processing the substrings and how many do you have? If you process them one at a time, and have a lot, a generator may be a good way to go for efficiency Commented Mar 3, 2014 at 20:48
  • 2
    Have you determined that you need the most efficient implementation? Programmers are notoriously bad at predicting where their bottlenecks will be. I advise that you code using the clear and obvious solution and then optimize if the performance is unacceptable. (I do this all the time and it is exceedingly rare that I have to go back and optimize even though I process large data sets.) Commented Mar 3, 2014 at 21:11

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would if I could, but I can't improve on it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.