Creating complex strings is, in many ways, the polar opposite of parsing a complex string. We generally find that we'll use a template with substitution rules to put data into a more complex format.

Modern Python Cookbook

Creating complex strings is, in many ways, the polar opposite of parsing a complex string. We generally find that we'll use a template with substitution rules to put data into a more complex format.
Let's say we have pieces of data that we need to turn into a nicely formatted message. We might have data including the following:
>>> id = "IAD" >>> location = "Dulles Intl Airport" >>> max_temp = 32 >>> min_temp = 13 >>> precipitation = 0.4
And we'd like a line that looks like this:
IAD : Dulles Intl Airport : 32 / 13 / 0.40
'{id} : {location} : {max_temp} / {min_temp} / {precipitation}'
It would look like this:
'{id:s} : {location:s} : {max_temp:d} / {min_temp:d} / {precipitation:f}'
'{id:3d} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'
>>> '{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'.format( ... id=id, location=location, max_temp=max_temp, ... min_temp=min_temp, precipitation=precipitation ... ) 'IAD : Dulles Intl Airport : 32 / 13 / 0.40'
We've provided all of the variables by name in the format() method of the template string. This can get tedious. In some cases, we might want to build a dictionary object with the variables. In that case, we can use the format_map() method:
>>> data = dict( ... id=id, location=location, max_temp=max_temp, ... min_temp=min_temp, precipitation=precipitation ... ) >>> '{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'.format_map(data) 'IAD : Dulles Intl Airport : 32 / 13 / 0.40'
We'll return to dictionaries in Chapter 4, Build-in Data Structures – list, set, dict.
The built-in vars() function builds a dictionary of all of the local variables for us:
>>> '{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'.format_map( ... vars() ... ) 'IAD : Dulles Intl Airport : 32 / 13 / 0.40'
The vars() function is very handy for building a dictionary automatically.
The string format() and format_map() methods can do a lot of relatively sophisticated string assembly for us.
The basic feature is to interpolate data into a string based on names of keyword arguments or keys in a dictionary. Variables can also be interpolated by position—we can provide position numbers instead of names. We can use a format specification like {0:3s} to use the first positional argument to format().
We've seen three of the formatting conversions—s, d, f—there are many others. Details are in Section 6.1.3 of the Python Standard Library. Here are some of the format conversions we might use:
We have a number of prefixes we can use for these different types. The most common one is the length. We might use {name:5d} to put in a 5-digit number. There are several prefixes for the preceding types:
There are some times when we won't use a {name:format} specification. Sometimes we'll need to use a {name!conversion} specification. There are only three conversions available.
In Chapter 6, Basics of Classes and Objects, we'll leverage the idea of the {name!r} format specification to simplify displaying information about related objects.
A handy debugging hack this:
print("some_variable={some_variable!r}".format_map(vars()))
The vars() function—with no arguments—collects all of the local variables into a mapping. We provide that mapping for format_map(). The format template can use lots of {variable_name!r} to display details about various objects we have in local variables.
Inside a class definition we can use techniques such as vars(self). This looks forward to Chapter 6, Basics of Classes and Objects:
>>> class Summary: ... def __init__(self, id, location, min_temp, max_temp, precipitation): ... self.id= id ... self.location= location ... self.min_temp= min_temp ... self.max_temp= max_temp ... self.precipitation= precipitation ... def __str__(self): ... return '{id:3s} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'.format_map( ... vars(self) ... ) >>> s= Summary('IAD', 'Dulles Intl Airport', 13, 32, 0.4) >>> print(s) IAD : Dulles Intl Airport : 32 / 13 / 0.40
Our class definition includes a __str__() method. This method relies on vars(self) to create a useful dictionary of just the attribute of the object.
Change the font size
Change margin width
Change background colour