insert thousands separators

John Machin sjmachin at lexicon.net
Fri Jun 13 17:00:15 EDT 2003


Nick Vargish <nav at adams.patriot.net> wrote in message news:<yyyvfv9hpj9.fsf at adams.patriot.net>...
> Marcus Bergmann <marcus.bergmann at isst.fhg.de> writes:
> 
> > how can I insert thousands separators into an integer or a string,
> > e.g. 1000000 to 1.000.000?
> 
> You may need to modify the following to match the "integer or string"
> part of your request. commafy() here accepts and integer but returns a
> string...

     commafy(1004) -> '1,7'
     commafy(1000007) -> '1,0,7'

This is interesting but possibly not quite what the OP was looking for.


> def commafy(val):
>     """Returns a string version of val with commas every thousandth
>     place."""
>     return val < 0 and '-' + commafy(abs(val)) \
>            or val < 1000 and str(val) \
>            or commafy(val / 1000) + ',' + commafy(val % 1000)

Try pinning ".zfill(3)" to its tail.




More information about the Python-list mailing list