Commafying an integer

A quick function to comma separate thousands in an integer or float.


Sometimes when working with integers that will be interpreted as monetary values, it is necessary to format the integer into a string containing commas between the thousands boundaries. This is a simple recursive regexp function to do just that. It is easily confused if your integer or float doesn't really look like one, but stick to just those input values and it will work fine.

import re

def comma_me(amount):
    orig = amount
    new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', amount)
    if orig == new:
        return new
    else:
        return comma_me(new)

f = 12345678
print comma_me(`f`)
Output: 12,345,678

code.activestate.com ↗