Python 2.6中的Str.format()出错,而2.7则没有。

15

我有一些在Python 2.7中运行良好的代码。

Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import stdout
>>> foo = 'Bar'
>>> numb = 10
>>> stdout.write('{} {}\n'.format(numb, foo))
10 Bar
>>>

但是在2.6版本中,我遇到了一个ValueError异常。

Python 2.6.8 (unknown, Jan 26 2013, 14:35:25) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from sys import stdout
>>> foo = 'Bar'
>>> numb = 10
>>> stdout.write('{} {}\n'.format(numb, foo))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: zero length field name in format
>>>

当查阅文档(2.62.7)时,我注意到没有提到两个版本之间是否有更改。这是怎么回事?

2个回答

28

Python 2.6及以下版本(以及Python 3.0)要求您对占位符进行编号:

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

如果在 Python 2.7 和 Python 3.1 及以上版本中省略编号,则隐式使用编号,请参见文档

从版本 2.7 开始更改:位置参数规范可以省略,因此 '{} {}' 等同于 '{0} {1}'

隐式编号很受欢迎;这里的许多示例都使用它,因为这样更容易构建快速的格式化字符串。在开发必须仍支持 2.6 的项目时,我曾经忘记过它们。


谢谢。我太忙于查看方法本身的文档,以至于错过了开头的文字。 - Mogget

5

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接