Splitting a string into substrings of equal size

Simon Forman sajmikins at gmail.com
Sun Aug 16 21:36:20 CEST 2009


On Aug 14, 8:22 pm, candide <cand... at free.invalid> wrote:
> Suppose you need to split a string into substrings of a given size (except
> possibly the last substring). I make the hypothesis the first slice is at the
> end of the string.
> A typical example is provided by formatting a decimal string with thousands
> separator.
>
> What is the pythonic way to do this ?
>
> For my part, i reach to this rather complicated code:
>
> # ----------------------
>
> def comaSep(z,k=3, sep=','):
>     z=z[::-1]
>     x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1]
>     return sep.join(x)
>
> # Test
> for z in ["75096042068045", "509", "12024", "7", "2009"]:
>     print z+" --> ", comaSep(z)
>
> # ----------------------
>
> outputting :
>
> 75096042068045 -->  75,096,042,068,045
> 509 -->  509
> 12024 -->  12,024
> 7 -->  7
> 2009 -->  2,009
>
> Thanks

FWIW:

def chunks(s, length=3):
    stop = len(s)
    start = stop - length
    while start > 0:
        yield s[start:stop]
        stop, start = start, start - length
    yield s[:stop]


s = '1234567890'
print ','.join(reversed(list(chunks(s))))
# prints '1,234,567,890'



More information about the Python-list mailing list