Formating strings in Python

I always forget how to use the format() method for str objects in Python, so here is a summary and a set of useful examples.

For more details, look at those two pages:

Basic formatting

The method basically works like this:

>>> '{} {}'.format('one', 'two')
one two
>>> '{} {}'.format(1, 2)
1 2
>>> '{1} {0} {1}'.format(1, 2)
2 1 2

Table summary

The general form of a standard format specifier is:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | ...
type        ::=  ... | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Left, center, right justifications: align = <, ^, >.

Some of the element representations depending on the type:

Type Meaning
‘s’ String format. This is the default type for strings and may be omitted or replaced by None
‘d’ Decimal Integer. Outputs the number in base 10. It may be omitted or replaced by None
‘e’ Scientific notation with exponent. You can also use ‘E’ to have an upper case separator.
‘f’ Displays the number as a fixed-point number. The default precision is 6
‘g’ General format. This will fall bakc to ‘e’ or ‘f’ depending on the magnitude of the number to format

Useful examples

I am usually interested in printing numbers, so here are a few examples that can become handy.

Write floating points (x, y, z coordinates):

>>> '{:<4} {:10.5f} {:10.5f} {:10.5f}'.format( 'H', 0.0, 0.0, 1.0 )
'H       0.00000    0.00000    1.00000'

Unpack array or list:

>>> line = ['H', 0.0, 0.0, 1.0]
>>> '{:<2} {:13.6f} {:13.6f} {:13.6f}\n'.format(*line)
'H       0.000000      0.000000      1.000000\n'

Padding number in scientific format with zeros:

>>> '{:015.3e}'.format( 3.141592653589793 )
'0000003.142e+00'

Accessing items:

>>> line = ['H', 0.0, 0.0, 1.0]
>>> '{0[0]:<2} {0[1]:13.6f} {0[2]:13.6f} {0[3]:13.6f}\n'.format(line)
'H       0.000000      0.000000      1.000000\n'

Accessing attributes:

>>> import math
>>> 'PRINT e={0.e:^10} AND pi={0.pi:<10}'.format(math)
'PRINT e=2.71828182846 AND pi=3.14159265359'