Formate a number with commas

N

noydb

How do you format a number to print with commas?

Some quick searching, i came up with:
'2,348,721'


I'm a perpetual novice, so just looking for better, slicker, more
proper, pythonic ways to do this.

Thanks!
 
N

Neil Cerutti

How do you format a number to print with commas?

Some quick searching, i came up with:

'2,348,721'

I'm a perpetual novice, so just looking for better, slicker,
more proper, pythonic ways to do this.

I think you've found an excellent way to do it.
 
P

Peter Otten

noydb said:
How do you format a number to print with commas?

Some quick searching, i came up with:

'2,348,721'


I'm a perpetual novice, so just looking for better, slicker, more
proper, pythonic ways to do this.
'1,234'
 
A

Alain Ketterlin

noydb said:
How do you format a number to print with commas?

This sets the locale according to the environment (typically LANG---I'm
talking about linux, don't know others).
'2,348,721'

This would not give the same result in environments with other locales
(typically de or fr or ...)

Anyway, it's probably the right thing to do: the user will get numbers
written according to its own locale.

If you really want commas whatever locale you're running in, you will
need to use setlocale to change number formatting to a locale that uses
commas. For instance:

locale.setlocale(LC_NUMERIC,"en_US.utf8")
locale.format('%d', 2348721, True)

-- Alain.
 
J

John Posner

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
 
T

Terry Reedy

Argh. The 2.7 docs say it was added in 2.7, but the 3.3a0 docs say it
was added in 3.1 (Guido's backporting time machine messes with
"causality").

Python 2 docs refer to Python 2.
Python 3 docs refer to Python 3.
So 'it' was in neither 2.6 nor 3.1.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top