Mog*_*get 15 python string-formatting backwards-compatibility python-2.6 python-2.7
我有一些在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
>>>
Run Code Online (Sandbox Code Playgroud)
但是在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
>>>
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 26
Python 2.6及之前(以及Python 3.0)要求您为占位符编号:
'{0} {1}\n'.format(numb, foo)
Run Code Online (Sandbox Code Playgroud)
如果在Python 2.7和Python 3.1及更高版本中省略,则编号是隐式的,请参阅文档:
在版本2.7中更改:位置参数说明符可以省略,因此
'{} {}'等效于'{0} {1}'.
隐式编号很受欢迎; Stack Overflow上有很多例子使用它,因为这样更容易制作快速格式字符串.在处理必须支持2.6的项目时,我忘了不止一次地包含它们.
这是在这里的文档中:http :
//docs.python.org/2/library/string.html#format-string-syntax
大约在该部分的一半处:
在版本2.7中更改:可以省略位置参数说明符,因此
'{} {}'等效于'{0} {1}'。
| 归档时间: |
|
| 查看次数: |
8732 次 |
| 最近记录: |