insert thousands separators

Michael Sparks zathras at thwackety.com
Fri Jun 13 15:58:18 EDT 2003


On Friday 13 June 2003 15:52, Marcus Bergmann wrote:
...
> how can I insert thousands separators into an integer or a string, e.g.
> 1000000 to 1.000.000?

A "correct" way:
>>> import locale
>>> locale.getlocale(locale.LC_NUMERIC)
['en_GB', 'iso8859-1']
>>> locale.format("%d",1000000,1)
'1,000,000'

A way of doing it without division:

def commafy(num,sep=",",floatsep="."):
  convert,nonIntPart,r = num,None,""
  if not isinstance(num,int):
      convert=int(num)
      nonIntPart=num-int(num)
  revd=str(convert)[-1::-1]
  l=len(revd)
  for i in xrange(0,l,3):
     r += revd[i:i+3]
     if i<l-3:
       r += sep
  r=r[-1::-1]
  if nonIntPart:
     r = r+floatsep+str(nonIntPart)[2::]
  return r

>>> commafy(1000000)
'1,000,000'


Michael
-- 
Ask five economists and you'll get five different explanations (six if
one went to Harvard).
		-- Edgar R. Fiedler






More information about the Python-list mailing list