Split a string by length

Eyal Lotem gnupeaker at yahoo.com
Thu Mar 25 05:20:34 EST 2004


I am not sure this is the best method, but a very
useful function I've been using is:

def divide(seq, size):
    return [seq[i:i+size]  for i in xrange(0,
len(seq), size)]

>>> divide('aabbcc', 2)
['aa', 'bb', 'cc']

(Works on non-strings too)

I put it in a common library and I reuse it all the
time.
I'd love to see it in the standard library, but until
then.. :)

--- Pascal <pascal.parent at free.fr> wrote:
> Hello,
> How can I do to simulate this way:
> 'aabbcc'.split(2) -> ['aa', 'bb', 'cc']
> I tried with a 'slice' but this didn't run:
> [item for item in 'aabbcc'[::2]] -> ['a', 'b', 'c']
> Thanks.


__________________________________
Do you Yahoo!?
Yahoo! Finance Tax Center - File online. File on time.
http://taxes.yahoo.com/filing.html




More information about the Python-list mailing list