Formate a number with commas
John Posner
jjposner at optimum.net
Thu Feb 9 17:57:42 EST 2012
On 2:59 PM, noydb wrote:
> How do you format a number to print with commas?
I would readily admit that both the "locale" module and "format" method
are preferable to this regular expression, which certainly violates the
"readability counts" dictum:
r"(?<=\d)(?=(\d\d\d)+$)"
# python 2.6.6
import re
find_blocks = re.compile(r"(?<=\d)(?=(\d\d\d)+$)")
for numstr in "1 12 123 1234 12345 123456 1234567 12345678".split():
print find_blocks.sub("," , numstr)
output is:
1
12
123
1,234
12,345
123,456
1,234,567
12,345,678
-John
More information about the Python-list
mailing list