Next / Previous / Contents / TCC Help System / NM Tech homepage

3.4. The string format method

One of the commonest string operations is to combine fixed text and variable values into a single string. For example, maybe you have a variable named nBananas that contains the number of bananas, and you want to format a string something like "We have 27 bananas today". Here's how you do it:

>>> nBananas = 54
>>> "We have {0} bananas today".format(nBananas)
'We have 54 bananas today'

Here is the general form of the string format operation:

S.format(p0, p1, ..., k0=e0, k1=e1, ...)

In this form:

Examples:

>>> "We have {0} bananas.".format(27)
'We have 27 bananas.'
>>> "We have {0} cases of {1} today.".format(42, 'peaches')
'We have 42 cases of peaches today.'
>>> "You'll have {count} new {thing}s by {date}".format(
...     count=27, date="St. Swithin's Day", thing="cooker")
"You'll have 27 new cookers by St. Swithin's Day"

You can control the formatting of an item by using a format code of the form “{N:type}”, where N is the number or name of the argument to the .format() method, and type specifies the details of the formatting.

The type may be a single type code like s for string, d for integer, or f for float.

>>> "{0:d}".format(27)
'27'
>>> "{0:f}".format(27)
'27.000000'
>>> "{animal:s}".format(animal="sheep")
'sheep'

You may also include a field size just before the type code. With float values, you can also specify a precision after the field size by using a “.” followed by the desired number of digits after the decimal.

>>> "({bat:8s})".format(bat='fruit')
'(fruit   )'
>>> "{0:8f}".format(1.0/7.0)
'0.142857'
>>> "{n:20.11f}".format(n=1.0/7.0)
'       0.14285714286'
>>> "{silly:50.40f}".format(silly=5.33333)
'        5.3333300000000001261923898709937930107117'

Notice in the last example above that it is possible for you to produce any number of spurious digits beyond the precision used to specify the number originally! Beware, because those extra digits are utter garbage.

When you specify a precision, the value is rounded to the nearest value with that precision.

>>> "{0:.1f}".format(0.999)
'1.0'
>>> "{0:.1f}".format(0.99)
'1.0'
>>> "{0:.1f}".format(0.9)
'0.9'
>>> "{0:.1f}".format(0.96)
'1.0'
>>> "{0:.1f}".format(0.9501)
'1.0'
>>> "{0:.1f}".format(0.9499999)
'0.9'

The “e” type code forces exponential notation. You may also wish to use the “g” (for general) type code, which selects either float or exponential notation depending on the value.

>>> avo = 6.022e23
>>> "{0:e}".format(avo)
'6.022000e+23'
>>> "{0:.3e}".format(avo)
'6.022e+23'
>>> "{num:g}".format(num=144)
'144'
>>> "{num:g}".format(num=avo)
'6.022e+23'

By default, strings are left-justified within the field size and numbers are right-justified. You can change this by placing an alignment code just after the “:”: “<” to left-align the field, “^” to center it, and “>” to right-align it.

>>> "/{0:<6s}/".format('git')
'/git   /'
>>> "/{0:^6s}/".format('git')
'/ git  /'
>>> "/{0:>6s}/".format('git')
'/   git/'
>>> '*{count:<8d}*'.format(count=13)
'*13      *'

Normally, short values are padded to length with spaces. You can specify a different padding character by placing it just after the “:”.

>>> "{0:08d}".format(17)
'00000017'
"{film:@>20s}".format(film='If')
'@@@@@@@@@@@@@@@@@@If'
>>> "{film:@^20s}".format(film='If')
'@@@@@@@@@If@@@@@@@@@'

If you need to produce any “{” or “}” characters in the result, you must double them within the format code.

>>> "Set {0}: contents {{red, green, blue}}".format('glory')
'Set glory: contents {red, green, blue}'

One thing we sometimes need to is to format something to a size that is not known until the program is running. For example, suppose we want to format a ticket number from a variable named ticket_no, with left zero fill, and the width is given by a variable named how_wide. This would do the job:

>>> how_wide = 8
>>> ticket_no = 147
>>> "Ticket {num:0{w}d}".format(num=ticket_no, w=how_wide)
'Ticket 00000147'

Here, where the width is expected, “{w}” appears. Because there is a keyword argument that is effectively w=8, the value "8" is used for the width.

Note

The string .format() method has been available only since Python 2.6. If you are looking at older code, you may see a different technique using the “%” operator. For example, 'Attila the %s' % 'Bun' yields 'Attila the bun'. For an explanation, see the Python library documentation. However, the old format operator is deprecated.