[Tutor] Comma Chameleon?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 25 Mar 2002 14:50:19 -0800 (PST)


On Mon, 25 Mar 2002, Curtis Larsen wrote:

> <grin>
> I'm  probably missing it, but isn't there some sort of formatting
> option for use with the 'print' command that will automagically insert
> commas into a number?  If not, what's the best Pythonic method to do
> this?  (Note: I don't need currency or a +/-: I just want 123456789 to
> look like 123,456,789.)

Actually, it doesn't appear to be built in.  I know I've seen this
somewhere in the Zope source code, so perhaps we can just yank it out of
Zope... ah, there it is!

In Zope, variables can be displayed with a "thousands_commas" attribute,
and the source code that does this is in DocumentTemplate/DT_Var.py.  It
might be educational to see what "production" code looks like.

Here's the relevant fragment that adds commas in:

###
def thousands_commas(v, name='(Unknown name)', md={},
                     thou=re.compile(
                         r"([0-9])([0-9][0-9][0-9]([,.]|$))").search):
    v=str(v)
    vl=v.split('.')
    if not vl: return v
    v=vl[0]
    del vl[0]
    if vl: s='.'+'.'.join(vl)
    else: s=''
    mo=thou(v)
    while mo is not None:
        l = mo.start(0)
        v=v[:l+1]+','+v[l+1:]
        mo=thou(v)
    return v+s
###

This isn't as bad as it might look.  You can ignore or remove the 'name'
and 'md' parameters --- I think they're specific to Zope --- but
everything else appears to try to do the "right" thing, no matter how ugly
the input is.  *grin* It even tries to treat floating point numbers
properly.

The approach they take is to use a regular expression to grab chunks of
thousands from a number, and add some decorative commas, until there's no
more commas to plug in.

Here's an example of it in action:

###
>>> thousands_commas(1234567890)
'1,234,567,890'
>>> thousands_commas(123456.7890)
'123,456.789'
###


Hope this helps!