print formatting

Peter Otten __peter__ at web.de
Sat Mar 13 14:37:50 CET 2010


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#formatstrings

Peter



More information about the Python-list mailing list