chunking a long string?

Skip Montanaro skip at pobox.com
Fri Nov 8 19:04:55 CET 2013


> I have a long string (several Mbytes).  I want to iterate over it in manageable chunks (say, 1 kbyte each).

You don't mention if the string is in memory or on disk. If it's in memory:

>>> for i in range(0, len(s), 10):
...   print repr(s[i:i+10])
...
'this is a '
'very long '
'string'

If your string is on disk, just loop over an open file object, reading
your chunk size every pass of the loop.

Skip



More information about the Python-list mailing list