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


Groups > comp.lang.python > #89879

Re: Best way to use globally format

From Peter Otten <__peter__@web.de>
Subject Re: Best way to use globally format
Date 2015-05-03 18:16 +0200
Organization None
References <87wq0pk7pf.fsf@Equus.decebal.nl>
Newsgroups comp.lang.python
Message-ID <mailman.70.1430669817.12865.python-list@python.org> (permalink)

Show all headers | View raw


Cecil Westerhof wrote:

> I have a file where I used a lot of {0}, {1} and {2}. Most but not all
> are changed to {0:.3E}, {1:.3E} and {2:.3E}. But when I want to change
> the format I come in dependency hell.
> 
> I could do something like:
>     format = ':.3E'
>     fmt0   = '{0' + format + '}
>     fmt1   = '{1' + format + '}
>     fmt2   = '{2' + format + '}
> 
> and replace occurrences of:
>     'before {0} after'
> with:
>     'before ' + fmt0 + ' after'
> 
> But that does not really make me happy. Is there a better way?
 
There's limited support for nesting {...}:

>>> "{0:{fmt}}, {1:{fmt}}, {2:{fmt}}".format(1.12345789, 2., 3., fmt=".3E")
'1.123E+00, 2.000E+00, 3.000E+00'
>>> "{0:{fmt}}, {1:{fmt}}, {2:{fmt}}".format(1.12345789, 2., 3., fmt="6.2")
'   1.1,    2.0,    3.0'
>>> "{0:{fmt}}, {1:{fmt}}, {2:{fmt}}".format(1.12345789, 2., 3., fmt="06.2")
'0001.1, 0002.0, 0003.0'

Converting the numbers to string first may be clearer though:

>>> formatted_numbers = [format(x, "010.2") for x in [1.12345789, 2., 3.]]
>>> "{0}, {1}, {2}".format(*formatted_numbers)
'00000001.1, 00000002.0, 00000003.0'

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


Thread

Best way to use globally format Cecil Westerhof <Cecil@decebal.nl> - 2015-05-03 17:21 +0200
  Re: Best way to use globally format Peter Otten <__peter__@web.de> - 2015-05-03 18:16 +0200
  Re: Best way to use globally format Ben Bacarisse <ben.usenet@bsb.me.uk> - 2015-05-03 17:32 +0100

csiph-web