String formatting: % vs. .format vs. string literal

后端 未结 16 3313
青春惊慌失措
青春惊慌失措 2020-11-21 04:18

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

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 04:49

    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.

提交回复
热议问题