ActiveState Code

Recipe 302069: Generator for splitting a string on parts of equal size


Example: <pre>

>>> list(splitIterator("102030405", 2))
['10', '20', '30', '40', '5']
</pre>
Python
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]

Comments

  1. 1. At 2 p.m. on 23 jun 2005, John Wundes said:

    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>

  2. 2. At 2:01 p.m. on 23 jun 2005, John Wundes said:

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

  3. 3. At 3:24 p.m. on 26 jul 2005, Frank P Mora said:

    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']
    

Sign in to comment