Splitting a string into substrings of equal size

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Aug 15 03:00:52 CEST 2009


En Fri, 14 Aug 2009 21:22:57 -0300, candide <candide at free.invalid>  
escribió:

> 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 ?

py> import locale
py> locale.setlocale(locale.LC_ALL, '')
'Spanish_Argentina.1252'
py> locale.format("%d", 75096042068045, True)
'75.096.042.068.045'

:)

> For my part, i reach to this rather complicated code:

Mine isn't very simple either:

py> def genparts(z):
...   n = len(z)
...   i = n%3
...   if i: yield z[:i]
...   for i in xrange(i, n, 3):
...     yield z[i:i+3]
...
py> ','.join(genparts("75096042068045"))
'75,096,042,068,045'

-- 
Gabriel Genellina




More information about the Python-list mailing list