[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

print formatting

vsoler

3/13/2010 1:17:00 PM

Hello,

My script contains a print statement:

print '%40s %15d' % (k, m)

However,

1- the string is right adjusted, and I would like it left
adjusted
2- the number is a decimal number, and I would like it with
the thousands separator and 2 decimals

If possible, the thousands separator and the decimal separator should
use my local settings.

Is there any way to achieve this?
2 Answers

Steve Holden

3/13/2010 1:32:00 PM

0

vsoler wrote:
> Hello,
>
> My script contains a print statement:
>
> print '%40s %15d' % (k, m)
>
> However,
>
> 1- the string is right adjusted, and I would like it left
> adjusted
> 2- the number is a decimal number, and I would like it with
> the thousands separator and 2 decimals
>
> If possible, the thousands separator and the decimal separator should
> use my local settings.
>
> Is there any way to achieve this?

Left-alignment is achieved by using a negative width.

You can use the locale module to generate thousands-separated numeric
string representations:

>>> from locale import *
>>> setlocale(LC_ALL, '') # locale is otherwise 'C'
'en_US.UTF-8'
>>> locale.format("%12.3f", 123456.789, grouping=False)
' 123456.789'
>>> locale.format("%12.3f", 123456.789, grouping=True)
' 123,456.789'

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pyco...
Holden Web LLC http://www.hold...
UPCOMING EVENTS: http://holdenweb.event...

Peter Otten

3/13/2010 1:38:00 PM

0

vsoler wrote:

> My script contains a print statement:
>
> print '%40s %15d' % (k, m)
>
> However,
>
> 1- the string is right adjusted, and I would like it left
> adjusted
> 2- the number is a decimal number, and I would like it with
> the thousands separator and 2 decimals
>
> If possible, the thousands separator and the decimal separator should
> use my local settings.
>
> Is there any way to achieve this?

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'de_DE.UTF-8'

Traditional:
>>> print '%-40s|%15s' % (k, locale.format("%d", m, grouping=True))
hello | 1.234.567

New:
>>> "{0:<40} {1:15n}".format(k, m)
'hello 1.234.567'

See also:
http://docs.python.org/dev/py3k/library/string.html#for...

Peter