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

后端 未结 16 2720
青春惊慌失措
青春惊慌失措 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:58

    But one thing is that also if you have nested curly-braces, won't work for format but % will work.

    Example:

    >>> '{{0}, {1}}'.format(1,2)
    Traceback (most recent call last):
      File "", line 1, in 
        '{{0}, {1}}'.format(1,2)
    ValueError: Single '}' encountered in format string
    >>> '{%s, %s}'%(1,2)
    '{1, 2}'
    >>> 
    

提交回复
热议问题