Thousand Seperator

Paul M¢Nett p at ulmcnett.com
Fri Mar 14 13:42:17 EDT 2008


Eddie Corns wrote:
> ewanfisher at gmail.com writes:
> 
>> I'm trying to find some code that will turn:
> 
>> 100 -> 100
>> 1000 -> 1,000
>> 1000000 -> 1,000,000
>> -1000 -> -1,000
> 
>> I know that can be done using a regular expression. In Perl I would do
>> something like:
> 
>> sub thousand {
>>        $number = reverse $_[0];
>>        $number =~ s/(\d\d\d)(?=\d)(?!d*\.)/$1,/g;
>>        return scalar reverse $number;
>> }
> 
>> But I cannot find how to do this in Python.
> 
> Look at the locale module.  If you're producing the numbers yourself then they
> get printed in that format otherwise you can convert them to numbers first.

Specifically:

import locale
locale.setlocale(locale.LC_ALL, '')
for trial in (100, 1000, 1000000, -1000):
	print trial, locale.format("%0f", trial, True)

If that results in no comma separators, then you may need to set the 
locale specifically, such as:

 >>> locale.setlocale(locale.LC_ALL, 'en_us')
'en_us'
 >>> for trial in (100, 1000, 100000, -1000):
...     print trial, locale.format("%.0f", trial, True)
...
100 100
1000 1,000
100000 100,000
-1000 -1,000

Paul



More information about the Python-list mailing list