Python - comparison of old and new string formatters
Archive - Originally posted on "The Horse's Mouth" - 2014-12-22 07:55:14 - Graham EllisThe % operator in Python when applied to a string object formats the object to the right using the format specifier to the left, using the same notations as the C function sprintf.
For example:
>>> j = 1.0 / 7.0
>>> print j
0.142857142857
>>> print "j has a value %.2f !!" % j
j has a value 0.14 !!
>>>
That's good and effective, but lacks some of the flexibility that's desirable, and could be provided these days.
So - from Python 2.6 a format method has been provided on string objects,
using a {} notation with an extended capability in place of %:
>>> print "j has a value {0:.2f} !!".format(j)
j has a value 0.14 !!
>>>
The "0" in the placeholder indicates that this element is to be filled in using element No. 0 from the tuple that's passed in to the format method. So you're allowed to re-use paramaters, specify them in different orders, ignore values if you wish (e.g. a changing format string) and you can even use named values from a dict.
>>> filler = {"person":"porridge", "wall":"Polyfilla"}
>>> print "Fill youself with {person} and your home with {wall}".format(**filler)
Fill youself with porridge and your home with Polyfilla
>>>
In Python 2.7, you can also leave out the position specifier - if you don't give a name or a number, it defaults to first value filled to first set of {}, second value to second set, etc.
An example (showing old and new styles for the same data) - [here] from last week's Python course. And there's a further example (updated, from the notes) [here].