[Tutor] Splitting a string into n-sized bytes

Kent Johnson kent37 at tds.net
Wed Mar 15 11:52:22 CET 2006


Steve Nelson wrote:
> Indeed - as I now have a function:
> 
> def nsplit(s, n):
>   return [s[i:i+n] for i in range(0, len(s), n)]
> 
> Incidentally I am currently going with:
> 
> def nsplit(s, n):
>   while s:
>    yield s[:n]
>    s = s[n:]

You can write the generator function to use the same method as the list 
comp and avoid creating all the intermediate (partial) lists:

def nsplit(s, n):
   for i in range(0, len(s), n):
     yield s[i:i+n]

One of the cool things about generators is that they make it so easy to 
maintain state between yields.

In Python 2.4, all you have to do is rewrite your original list comp to 
a generator comprehension:

def nsplit(s, n):
   return (s[i:i+n] for i in range(0, len(s), n))

Kent



More information about the Tutor mailing list