I feel stoopid ... this code is to verbose

John La Rooy larooy at xtar.co.nz
Sun Jun 16 02:57:01 EDT 2002


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
> 

As other people have pointed out already, the locale module is the way to go
but some people do find it a fun exercise too ;o)

(this breaks if you have more than 3 digits after the decimal point. what's
supposed to happen then anyway?)

import re
def StringSlicer(s):
	return re.sub("\\B(\d{3})(?=(\d{3})*(,\d*)?$)",".\\1",s.replace(".",","))

John



More information about the Python-list mailing list