Formatting a numerical string w/commas

Thomas A. Bryan tbryan at python.net
Mon Feb 21 18:51:45 EST 2000


steven moy wrote:
> 
> Is there an easy way to format a numerical string with commas
> in the appropriate places?  

Easy?  I don't know.  Equivalent to your commify?  Sure!
> 
> 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?

Sure...of course, I've done a bit of overkill here.
You can stick this in commify.py and do a 
from commify import commify
to use the function wherever you like.

################## commify.py ################
#!/bin/env python

import re
regex = re.compile(r'^(-?\d+)(\d{3})')

def commify(num, separator=','):
    """commify(num, separator) -> string

    Return a string representing the number num with separator inserted
    for every power of 1000.   Separator defaults to a comma.
    E.g., commify(1234567) -> '1,234,567'
    """
    num = str(num)  # just in case we were passed a numeric value
    more_to_do = 1
    while more_to_do:
        (num, more_to_do) = regex.subn(r'\1%s\2' % separator,num)
    return num

if __name__ == '__main__':

    test_vals = (12345,
                 -12345,
                 1234567,
                 -1234567,
                 1234567.89,
                 -1234567.89,
                 1234567.8901,
                 -1234567.8901)

    print "If you use '.' as your decimal indicator..."
    for number in test_vals:
        print commify(number)


    weirdo_test_vals = ('12345',
                 '-12345',
                 '1234567',
                 '-1234567',
                 '1234567,89',
                 '-1234567,89',
                 '1234567,8901',
                 '-1234567,8901')

    print "If you use ',' as your decimal indicator..."
    for number in weirdo_test_vals:
        print commify(number,'.')



More information about the Python-list mailing list