Python string formatting - the move from % to str.format
Archive - Originally posted on "The Horse's Mouth" - 2011-10-08 08:17:20 - Graham EllisThe % operator in Python has been a very clever and easy-to-use formatter, but has lacked the extensibility that's been incumbent on its structure and mirroring of the C sprintf function. Or - put another way - it was rather irritatingly running out of steam for some of the more complex formatting jobs, and users were having to write code and use modules to do whatshould really have been some fairly basic formatting.
At Python 2.6 the format method was added onto string object to provide a more flexible alternative, and as from Python 3 this will be / is the new standard.
The parentage of sprintf can still be seen in the new format method, although it's slighly longer to use.
Python 2.5:
print "The value %.2f is the result" % val
Python 2.6:
print "The value {0:.2f} is the result".format(val)
Python 2.7:
print "The value {:.2f} is the result".format(val)
The position parameter 0 from 2.6 has become optional
Python 3.x:
print ("The value {:.2f} is the result".format(val))
print is a function - as it always should have been - from Python 3.0
The string on which the fomat method is run is a template within which elements to be inserted are defined in curly braces. Each of these elements may comprise a number of parts - the main two of which specify what is to be inserted and how it is to be formatted. For example:
val = 1000 / 7 ; # integer example
print "The results is {0:4d} if you divide 1000 by 7".format(val)
uses the string {0:4d} to say "place the zeroth parameter to format - which is the value held in the val variable in my example - here. Output it to base 10 (decimal) and take up at least 4 character positions". There are a number of sensible defaults - the value will be right justified, left space filled if it doesn't need all the characer positions requested, for example.
With a formatter that's so flexible, you'll want to see plenty of examples and I have added an annotated program to show you a lot more - together with sample output - [here]. And we're moving over to using the String Formatter in new examples we write now that Python 2.5 and earlier is starting to get a little rarer. The "old stuff" still works so there's no need to go rushing to make changes to your existing codebase. In Python 3:
val = 12.0 / 17.0
print ("The value is %.3f - old style" % val)
print ("The value is {:.3f} - new style".format(val))
Which runs as follows:
wizard:oct11 graham$ python3 spy3.py
The value is 0.706 - old style
The value is 0.706 - new style
wizard:oct11 graham$
As even .. "as taught on our Python Courses" ;-)