Splitting a string into substrings of equal size

Jan Kaliszewski zuo at chopin.edu.pl
Fri Aug 14 22:40:05 EDT 2009


15-08-2009 Jan Kaliszewski <zuo at chopin.edu.pl> wrote:

> 15-08-2009 candide <candide 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.
>
> I'd use iterators, especially for longer strings...
>
>
> import itertools
[snip]

Err... It's too late for coding... Now I see obvious and simpler variant:

def separate(text, grouplen=3, sep=','):
     "separate('12345678') -> '123,456,78'"
     textlen = len(text)
     end = textlen - (textlen % grouplen)
     strings = (text[i:i+grouplen] for i in xrange(0, end, grouplen))
     return sep.join(itertools.chain(strings, (text[end:],)))

def back_separate(text, grouplen=3, sep=','):
     "back_separate('12345678') -> '12,345,678'"
     textlen = len(text)
     beg = textlen % grouplen
     strings = (text[i:i+grouplen] for i in xrange(beg, textlen, grouplen))
     return sep.join(itertools.chain((text[:beg],), strings))

print separate('12345678')
print back_separate('12345678')

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list