Best way to use globally format
Peter Otten
__peter__ at web.de
Sun May 3 12:16:41 EDT 2015
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'
More information about the Python-list
mailing list