1

I know that in Python there's the possibility of converting a given string into a list:

>>> h='ghilmnoPqzH'
>>> list(h)
['g', 'h', 'i', 'l', 'm', 'n', 'o', 'P', 'q', 'z', 'H']

But how can I split the list into given intervals? I.e., given the above string h if I set a parameter s=4 I should get

['ghi', 'lmn', 'oPq', 'zH']

This question is different from How do you split a list into evenly sized chunks in Python? because, if I use that function I get the following error:

<generator object chunks at 0x0296A030>

Community
  • 1
  • 1
james42
  • 307
  • 5
  • 16
  • Possible duplicate of [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – jub0bs Dec 08 '15 at 11:00
  • Not really. I have tried to apply that function and I get the error `` – james42 Dec 08 '15 at 11:06

1 Answers1

1
>>> interval = 3
>>> s = 'ghilmnoPqzH'
>>> [s[start:start + interval] for start in range(0, len(s), interval)]
['ghi', 'lmn', 'oPq', 'zH']
Mike Müller
  • 82,630
  • 20
  • 166
  • 161