As @Martijn Pieters implied, this would be trivially easy if you had a way to iterate an iterator by chunks (of n). And if you read that question, you do have a way to do that.
So, given the grouper
implementation from the itertools recipes (or anything else you prefer from that other question):
lines = [''.join(group) for group in grouper(50, my_string, '')]
Or, if you just want to print them out:
for group in grouper(50, my_string, ''):
print ''.join(group)
Once you know that grouper
exists, I think this is simpler than Joel Cornett's answer. Note that his didn't work in the first version, and had to be fixed; this one is pretty much impossible to get wrong. Anything that eliminates the possibility of fencepost errors is usually better; that's why we have for
-in
loops and enumerate
instead of C-style for
loops, and so on.
Here it is in action:
>>> my_string='1234567890'*49+'12'
>>> print my_string
123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012
>>> # That was ugly…
>>> for group in grouper(50, my_string, ''):
... print ''.join(group)
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012
>>> # Pretty!