Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #20119

Re: Formate a number with commas

Date 2012-02-09 17:57 -0500
From John Posner <jjposner@optimum.net>
Subject Re: Formate a number with commas
References <eb1973ef-913e-408a-b491-d1449c8434e2@c21g2000yqi.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.5620.1328830071.27778.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Formate a number with commas noydb <jenn.duerr@gmail.com> - 2012-02-09 12:08 -0800
  Re: Formate a number with commas Neil Cerutti <neilc@norwich.edu> - 2012-02-09 20:17 +0000
  Re: Formate a number with commas Peter Otten <__peter__@web.de> - 2012-02-09 21:39 +0100
  Re: Formate a number with commas Chris Rebert <clp2@rebertia.com> - 2012-02-09 12:51 -0800
  Re: Formate a number with commas Alain Ketterlin <alain@dpt-info.u-strasbg.fr> - 2012-02-09 22:13 +0100
  Re: Formate a number with commas Peter Otten <__peter__@web.de> - 2012-02-09 22:16 +0100
  Re: Formate a number with commas Chris Rebert <clp2@rebertia.com> - 2012-02-09 14:12 -0800
  Re: Formate a number with commas John Posner <jjposner@optimum.net> - 2012-02-09 17:57 -0500
  Re: Formate a number with commas Terry Reedy <tjreedy@udel.edu> - 2012-02-09 22:06 -0500

csiph-web