Formatting a numerical string w/commas

bjorn bjorn at roguewave.com
Mon Feb 21 16:48:48 EST 2000


import locale
locale.setlocale(locale.LC_ALL, 'us')
locale.format('%d', 123456, 3)
locale.format('%.3f', 12345.678, 3)

-- bjorn

steven moy wrote:

> Is there an easy way to format a numerical string with commas
> in the appropriate places?  I also want to be able to handle +/- and
> decimal places as well.  For example, I would want to convert
> -1234567.89 to -1,234,567.89.
>
> I know how to do it in Perl:
>
> sub commify {
>         local $_  = shift;
>         1 while s/^(-?\d+)(\d{3})/$1,$2/;
>         return $_;
> }
>
> Can anyone provide me with a Python equivalent?
>
> Thanks,
>
> -$
>
> --
> http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list