Splitting a string into substrings of equal size

Gregor Lingl gregor.lingl at aon.at
Mon Aug 17 19:14:57 EDT 2009


Simon Forman schrieb:
> 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 ?
>>
...
>> 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'

or:

 >>> def chunks(s, length=3):
         i, j = 0, len(s) % length or length
         while i < len(s):
                 yield s[i:j]
                 i, j = j, j + length

 >>> print(','.join(list(chunks(s))))
1,234,567,890
 >>> print(','.join(list(chunks(s,2))))
12,34,56,78,90
 >>> print(','.join(list(chunks(s,4))))
12,3456,7890

Regards,
Gregor



More information about the Python-list mailing list