next up previous contents
Next: File Objects Up: Input and Output Previous: Formatting Strings   Contents

Using Names in Format Strings

As an alternative to the method described in the previous section, where the arguments to be formatted had to be in a tuple, python allows you to use a dictionary to contain the values to be formatted, and to use the dictionary's keys within the format string for added readability. To use this feature, put the appropriate key, surrounded in parentheses, between the percent sign and the format code of the appropriate element in the format string. For example, suppose the information to be formatted in the previous section was stored in a dictionary as follows:
>>> info = {'quantity':7,'itemprice':.29,'totalprice':7 * .29}
Then we could produce the same result as the previous example with the following print statement:
>>> print '%(quantity)d items at %(itemprice)5.2f ' \
...       'per item gives a total of $%(totalprice)4.2f' % info  
7 items at  0.29 per item gives a total of $2.03
Notice that python concatenated the two pieces of the formatting string, due to the presence of the backslash at the end of the first line.



Phil Spector 2003-11-12