.format
was introduced in Python2.6 It is more powerful than %
.
The most common use:
>>> '{}, {}, {}'.format('a', 'b', 'c')
'a, b, c'
>>> '{2}, {1}, {0}, {1}'.format('a', 'b', 'c')
'c, b, a, b'
One may pass variables as named arguments:
>>> '({x}, {y}): {object}'.format(x=1, y=2, object='apple')
'(1,2): apple'
It's very convenient to use this with dictionary unpacking
>>> info = {'x': 1, 'y': 2, 'object': 'apple'}
>>> '({x}, {y}): {object}'.format(**info)
'(1,2): apple'
Or tuple arguments unpacking
info = ('a' 'b', 'c')
>>> '{2}, {1}, {0}, {1}'.format(*info)
'c, b, a, b'
There are also a lot of special formatters related to floats, hex, dates etc. For example
>>> '{0:.4f}'.format(342.34254234)
'342.3425'
and
>>> '{:06}'.format(123)
'000123'
Links: