# I feel stoopid ... this code is to verbose

Christophe Delord christophe.delord at free.fr
Fri Jun 14 12:39:45 EDT 2002

```If you want to split a number you can try this :

def nbSlicer(nb, chunkSize=3):
if nb==0: return "0"
l = []
b = 10**chunkSize
fmt = "%%0%dd"%chunkSize
while nb:
nb, r = divmod(nb, b)
l.insert(0,(nb and fmt or "%d")%r)
return '.'.join(l)

Or this if you prefer to split a string :

def stringSlicer(st, chunkSize=3):
l = []
while st:
l.insert(0,st[-3:])
st = st[:-3]
return '.'.join(l)

print nbSlicer(42000000)
print stringSlicer('42000000')

On Fri, 14 Jun 2002 18:19:29 +0200
Max M <maxm at mxm.dk> wrote:

> Hmm ... I am working on a problem. In Danish we have a number format
> that looks like:
>
> 42.000.000,00 which is 42 millions
>
> So I need to insert dot's at every three character from end of the
> string for the integer value of the number.
>
> Let's discard decimal points and just focus on the meat. I have written
> a funcion which works::
>
> def stringSlicer(string, chunkSize=3):
>      chunkList = []
>      reverseString = list(string)
>      reverseString.reverse()
>      for i in range(0, len(string), chunkSize):
>          chunk = reverseString[i:i+chunkSize]
>          chunk.reverse()
>          chunk = ''.join(chunk)
>          chunkList.append(chunk)
>      chunkList.reverse()
>      return '.'.join(chunkList)
>
>
> print stringSlicer('42000000')
>
>  >>> 40.000.000
>
> I just find that it's a lot of code for such a little function an it
> annoys my sense of aestetics. I have tried a lot of different approaches
> including using zip on a list like ['','','.'], and other weird stuff :-)
>
> I just cannot seem to find the nice 3-liner I expected from the
> beginning. Has anybody got a better solution ? I thought somebody might
> find it a fun exercise. Well I have...
>
>
> regards Max M
>

--

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V

```