- Create a template string from the result, replacing all of the data items with {} placeholders. Inside each placeholder, put the name of the data item.
'{id} : {location} : {max_temp} / {min_temp} / {precipitation}'
- For each data item, append :data type information to the placeholders in the template string. The basic data type codes are:
- s for string
- d for decimal number
- f for floating-point number
It would look like this:
'{id:s} : {location:s} : {max_temp:d} / {min_temp:d} / {precipitation:f}'
- Add length information where required. Length is not always required, and in some cases, it's not even desirable. In this example, though, the length information assures that each message has a consistent format. For strings and decimal numbers, prefix the format with the length like this: 19s or 3d. For floating-point numbers use a two part prefix like this: 5.2f to specify the total length of five characters with two to the right of the decimal point. Here's the whole format:
'{id:3d} : {location:19s} : {max_temp:3d} / {min_temp:3d} / {precipitation:5.2f}'
- Use the format() method of this string to create the final string:
>>> '{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.