Split a string by length

Anton Vredegoor anton at vredegoor.doge.nl
Thu Mar 25 17:00:19 CET 2004

Yermat <loic at fejoz.net> wrote:

>Make it simple... Finally the chunklist or chunks are my favorite for 
>general chunk function. For string I would have use the regexp anyway...

Functions can be arguments too. Combining that with making them
optional and having a default:

from itertools import islice

def groupby(seq,n,exhaust = list):
    it = iter(seq)
    res = exhaust(islice(it,n))
    while res:
        yield res
        res = exhaust(islice(it,n))
def test():
    seq = [[],[],[],[],[]]
    print list(groupby(seq,2))
    s = 'aabbccdde'
    print list(groupby(s,2,''.join))

if __name__=='__main__':


[[[], []], [[], []], [[]]]
['aa', 'bb', 'cc', 'dd', 'e']


More information about the Python-list mailing list