Formatting a numerical string w/commas

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Feb 22 08:12:55 EST 2000


> Hmmm, well it seems I need to find an alternative then, since it's a huge
> pain to try to get the ISP hosting my servers to do anything, much less
> recompile something for me.

Ah, right. Yes, you can certainly compile _locale.c into _locale.so,
and use that - it won't require to modify the standard Python
installation, then. If you know what operating system your ISP is
using, you can probably compile it on any other installation of the
same system. For example, for Linux, it would be sufficient to know
what the Python version is, and what the major version of the C
library is (4, 5, or 6).

> To go back to my original question, if using the locale module is
> not an option, how can I write a function to insert commas in the
> appropriate places in a number, allowing for +/- as well as 2
> decimal places?  For example, I would want commify('-1234567.89') to
> return '-1,234,567.89').

It's probably possible with regular expressions as well, but I'd
rather use a more direct string operation, such as

import string
def commify(str):
  result = str[-6:]
  str = str[:-6]
  while len(str)>2:
    result = str[-3:] + ',' + result 
    str = str[:-3]
  if len(str)>0 and str[-1]!='-':
    return str+','+result
  return str+result

The loop initially knows that the last 6 characters (include '.' and
the 2 decimal places) don't need an commas, and then starts replacing
from the right end.

Hope this helps,
Martin




More information about the Python-list mailing list