insert thousands separators
Nick Vargish
nav at adams.patriot.net
Fri Jun 13 13:10:18 EDT 2003
Marcus Bergmann <marcus.bergmann at isst.fhg.de> writes:
> how can I insert thousands separators into an integer or a string,
> e.g. 1000000 to 1.000.000?
You may need to modify the following to match the "integer or string"
part of your request. commafy() here accepts and integer but returns a
string...
Nick
----------------- CUT HERE ------------------------------
#!/usr/bin/env python
#
# Algorithm from Bengt Richter
# Cleaned up a little by Nick Vargish
#
"""Return a string version of a value with commas every thousandth
place.
"""
def commafy(val):
"""Returns a string version of val with commas every thousandth
place."""
return val < 0 and '-' + commafy(abs(val)) \
or val < 1000 and str(val) \
or commafy(val / 1000) + ',' + commafy(val % 1000)
def _test_commafy():
"""Unit test for commafy() function."""
for i in [ 1, 12, 123, 1234, 12345, 123456, 1234567, 12345678,
123456789 ]:
print "%12s %12s" % (commafy(i), commafy(-i))
if __name__ == '__main__':
_test_commafy()
----------------- CUT HERE ------------------------------
--
#include<stdio.h> /* SigMask 0.3 (sig.c) 19990429 PUBLIC DOMAIN "Compile Me" */
int main(c,v)char *v;{return !c?putchar(*v-1)&&main(0,v+ /* Tweaks welcomed. */
1):main(0,"Ojdl!Wbshjti!=obwAqbusjpu/ofu?\v\1");} /* build: cc -o sig sig.c */
More information about the Python-list
mailing list