I feel stoopid ... this code is to verbose

Max M maxm at mxm.dk
Fri Jun 14 18:19:29 CEST 2002


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




More information about the Python-list mailing list