How to iterate through a sequence, grabbing subsequences?

Bruno Desthuilliers onurb at xiludom.gro
Fri Sep 29 16:54:32 CEST 2006

Matthew Wilson wrote:
> I wrote a function that I suspect may already exist as a python builtin,
> but I can't find it:
> def chunkify(s, chunksize):
>     "Yield sequence s in chunks of size chunksize."
>     for i in range(0, len(s), chunksize):
>         yield s[i:i+chunksize]
> I wrote this because I need to take a string of a really, really long
> length and process 4000 bytes at a time.
> Is there a better solution?

I don't know if it's better, but StringIO let you read a string as if it
was a file:

def chunkify(s, chunksize):
  f = StringIO.StringIO(long_string)
  chunk =
  while chunk:
    yield chunk
    chunk =

Now I'm sure someone will come up with a solution that's both far better
and much more obvious (at least if you're Dutch <g>)

bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"

More information about the Python-list mailing list