String formatting

One of the most interesting and frequently used string methods is format(). This supersedes, although does not replace, the string interpolation technique used in older versions of Python, and which we do not cover in this book. The format() method can be usefully called on any string containing so-called replacement fields which are surrounded by curly braces. The objects provided as arguments to format() are converted to strings and used to populate these fields. Here's an example:

>>> "The age of {0} is {1}".format('Jim', 32)
'The age of Jim is 32'

The field names, in this case 0 and 1, are matched up with the positional arguments to format(), and each argument is converted to a string behind the scenes.

A field name may be used more than once:

>>> "The age of {0} is {1}. {0}'s birthday is on {2}".format('Fred', 24, 'October 31')

However, if the field names are used exactly once and in the same order as the arguments, they can be omitted:

>>> "Reticulating spline {} of {}.".format(4, 23)
'Reticulating spline 4 of 23.'

If keyword arguments are supplied to format() then named fields can be used instead of ordinals:

>>> "Current position {latitude} {longitude}".format(latitude="60N", 
longitude="5E")

'Current position 60N 5E'

It's possible to index into sequences using square brackets inside the replacement field:

>>> "Galactic position x={pos[0]}, y={pos[1]}, z={pos[2]}".
format(pos=(65.2, 23.1, 82.2))

'Galactic position x=65.2, y=23.1, z=82.2'

We can even access object attributes. Here we pass the whole math module to format() using a keyword argument (Remember – modules are objects too!), then access two of its attributes from within the replacement fields:

>>> import math
>>> "Math constants: pi={m.pi}, e={m.e}".format(m=math)
'Math constants: pi=3.141592653589793 e=2.718281828459045'

Format strings also give us a lot of control over field alignment and floating-point formatting. Here's the same with the constants displayed to only three decimal places:

>>> "Math constants: pi={m.pi:.3f}, e={m.e:.3f}".format(m=math)
'Math constants: pi=3.142, e=2.718'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset