Str.format() for Python 2.6 gives error where 2.7 does not

后端 未结 2 1322
谎友^
谎友^ 2020-12-11 01:33

I have some code which works well in Python 2.7.

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type \"help\", \"copyright\", \"credits         


        
相关标签:
2条回答
  • 2020-12-11 01:48

    This is in the docs here:
    http://docs.python.org/2/library/string.html#format-string-syntax

    About halfway through that section:

    Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

    0 讨论(0)
  • 2020-12-11 01:56

    Python 2.6 and before (as well as Python 3.0) require that you number the placeholders:

    '{0} {1}\n'.format(numb, foo)
    

    The numbering, if omitted in Python 2.7 and Python 3.1 and up, is implicit, see the documentation:

    Changed in version 2.7: The positional argument specifiers can be omitted, so '{} {}' is equivalent to '{0} {1}'.

    The implicit numbering is popular; a lot of examples here on Stack Overflow use it as it is easier to whip up a quick format string that way. I have forgotten to include them more than once when working on projects that must support 2.6 still.

    0 讨论(0)
提交回复
热议问题