-1

In C++/C, I can write the following:

string s;
int window_len = 3;
for (int i = 0, j = window_len; j <= s.length(); i += window_len, j += window_len) {
  //do things with s.Slice(i, j)
}

Is there a pythonic way of expressing the above composite for loop?

jameszhao00
  • 7,213
  • 15
  • 62
  • 112
  • 1
    Possible duplicate of [What's the best way to split a string into fixed length chunks and work with them in Python?](http://stackoverflow.com/questions/18854620/whats-the-best-way-to-split-a-string-into-fixed-length-chunks-and-work-with-the) – DYZ Jan 17 '17 at 04:23
  • @DYZ That's pretty similar but not quite what I was looking for. chunkstring("abc", 2) returns "['ab', 'c']". The code above will return "['ab']" – jameszhao00 Jan 17 '17 at 04:27
  • You are right, there was an error in the snippet. – DYZ Jan 17 '17 at 04:29
  • Just add an extra check to remove the last element if the string isn't divisible by the chunk length – jackarms Jan 17 '17 at 04:29

3 Answers3

2

One way that using the fact that floor dividing the length of the string by the "group"-size will truncate remaining characters:

>>> string = 'abcdefghijklm'
>>> size=2

>>> [string[i*size:(i+1)*size] for i in range(len(string) // size)]
['ab', 'cd', 'ef', 'gh', 'ij', 'kl']

Or in a for-loop:

for i in range(len(string) // size):
    substr = string[i*size:(i+1)*size]
    # do stuff with substr
MSeifert
  • 145,886
  • 38
  • 333
  • 352
1

I think this gets at the concept in a similar way and doesn't require a lot of additional math:

strides = range(0, len(s)+1, window_len)
for i, j in zip(strides, strides[1:]):
    # do something with s[i:j]
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
  • You need to use `len(s)+1` as stop in your `range` though. I was just about to post that one too but you were faster :-) – MSeifert Jan 17 '17 at 04:48
0

Why, of course:

s = "Hello, world!"
[s[i:i + window_len] for i in range(0, len(s)-window_len+1, window_len)]
# ['Hel', 'lo,', ' wo', 'rld']
DYZ
  • 55,249
  • 10
  • 64
  • 93