[Tutor] Splitting a string into n-sized bytes

Smith smiles at worksmail.net
Wed Mar 15 04:42:55 CET 2006


| From: "Steve Nelson" 
| 
| Further to my previous puzzling, I've been working out the best way to
| chop a string up into n-sized words:
| 

I think the follow use of groupby is from Raymond Hettinger from ASPN recipes. The batch() function will return an iterable to you in user-definable sized sets.

####
from itertools import groupby
def batch(iterable, size):
    def ticker(x, s=size, a=[-1]):
        r = a[0] = a[0] + 1
        return r // s
    for k, g in groupby(iterable, ticker):
         yield g
s='this is my string to parse up.'
for i in batch(s,4):
    print list(i)
####

The output is lists of (in this case) 4 characters; the last group is shorter, but you already know how to fix that.

####
['t', 'h', 'i', 's']
[' ', 'i', 's', ' ']
['m', 'y', ' ', 's']
['t', 'r', 'i', 'n']
['g', ' ', 't', 'o']
[' ', 'p', 'a', 'r']
['s', 'e', ' ', 'u']
['p', '.']
####

/c


More information about the Tutor mailing list