I feel stoopid ... this code is to verbose
Eddie Corns
eddie at holyrood.ed.ac.uk
Fri Jun 14 13:17:21 EDT 2002
Max M <maxm at mxm.dk> writes:
>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
>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)
>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 :-)
Recursion and remembering that you can avoid reverse by chopping off the tail
end.
My contribution:
def commas (n,span=3,sep='.'):
def chop (x, acc=[]):
if not x: return acc
return chop (x[:-span], [x[-span:]]+acc)
return sep.join(chop(str(n)))
I called it that because that's what the Icon command is called (and I misread
the post first time through - eyesight must be going).
Eddie
More information about the Python-list
mailing list