Welcome, guest | Sign In | My Account | Store | Cart

Example: <pre>

>>> list(splitIterator("102030405", 2))
['10', '20', '30', '40', '5']
</pre>
Python, 4 lines
1
2
3
4
def splitIterator(text, size):
    assert size > 0, "size should be > 0"
    for start in xrange(0, len(text), size):
        yield text[start:start + size]

3 comments

John Wundes 18 years, 10 months ago  # | flag

another option... another implementation:

def chop(lst,chunksize):

    x = 0
    ret = []
    while x another implementation:

<pre>
def chop(lst,chunksize):

    x = 0
    ret = []
    while x

</pre>

John Wundes 18 years, 10 months ago  # | flag

Not sure what happened there... ASPN seems to have mangled my post...

Frank P Mora 18 years, 9 months ago  # | flag

list comprehension (abstraction).

>>> cf= lambda s,p: [ s[i:i+p] for i in range(0,len(s),p) ]

>>> cf('1a2b3c4d5e6f',2)
['1a', '2b', '3c', '4d', '5e', '6f']

>>> cfi= iter(cf('1a2b3c4d5e6f',2))
>>> [ i for i in cfi ]
['1a', '2b', '3c', '4d', '5e', '6f']
Created by Dmitry Vasiliev on Thu, 26 Aug 2004 (PSF)
Python recipes (4591)
Dmitry Vasiliev's recipes (9)

Required Modules

  • (none specified)

Other Information and Tasks