Split string by count of characters

Since you want to iterate in an unusual way, a generator is a good way to abstract that:

def chunks(s, n):
    """Produce `n`-character chunks from `s`."""
    for start in range(0, len(s), n):
        yield s[start:start+n]

nums = "1.012345e0070.123414e-004-0.1234567891.21423"
for chunk in chunks(nums, 12):
    print chunk

produces:

1.012345e007
0.123414e-00
4-0.12345678
91.21423

(which doesn’t look right, but those are the 12-char chunks)

Leave a Comment