Can Python format long integer 123456789 to 12,3456,789 ?

Warren Block wblock at wonkity.com
Sat Jun 3 00:47:24 EDT 2006


John Machin <sjmachin at lexicon.net> wrote:
> On 2/06/2006 9:08 AM, A.M wrote:
>> Hi,
>> 
>> Is there any built in feature in Python that can format long integer 
>> 123456789 to 12,3456,789 ?
>> 
>> Thank you,
>> Alan
>
> Not that I know of, but this little kludge may help:
> 8<---
> import re
>
> subber = re.compile(r'^(-?\d+)(\d{3})').sub
>
> def fmt_thousands(amt, sep):
>      if amt in ('', '-'):
>          return ''
>      repl = r'\1' + sep + r'\2'
>      while True:
>          new_amt = subber(repl, amt)
>          if new_amt == amt:
>              return amt
>          amt = new_amt
>
> if __name__ == "__main__":
>      for prefix in ['', '-']:
>          for k in range(11):
>              arg = prefix + "1234567890.1234"[k:]
>              print "<%s> <%s>" % (arg, fmt_thousands(arg, ","))
> 8<---

Why not just port the Perl "commify" code?  You're close to it, at least
for the regex:

# From perldoc perlfaq5
# 1 while s/^([-+]?\d+)(\d{3})/$1,$2/;

# Python version

import re

def commify(n):
    while True:
        (n, count) = re.subn(r'^([-+]?\d+)(\d{3})', r'\1,\2', n)
        if count == 0: break
    return n

-- 
Warren Block * Rapid City, South Dakota * USA



More information about the Python-list mailing list