Python 2.6 introduced the str.format() method with a slightly different syntax from the existing %
operator. Which is better and for what situations?
Pyt
Yet another advantage of .format
(which I don't see in the answers): it can take object properties.
In [12]: class A(object):
....: def __init__(self, x, y):
....: self.x = x
....: self.y = y
....:
In [13]: a = A(2,3)
In [14]: 'x is {0.x}, y is {0.y}'.format(a)
Out[14]: 'x is 2, y is 3'
Or, as a keyword argument:
In [15]: 'x is {a.x}, y is {a.y}'.format(a=a)
Out[15]: 'x is 2, y is 3'
This is not possible with %
as far as I can tell.