适用于Python 2.6的Str.format()给出了错误,其中2.7没有 [英] Str.format() for Python 2.6 gives error where 2.7 does not

查看:79
本文介绍了适用于Python 2.6的Str.format()给出了错误,其中2.7没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些可以在Python 2.7中正常工作的代码.

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" or "license" for more information.
>>> from sys import stdout
>>> foo = 'Bar'
>>> numb = 10
>>> stdout.write('{} {}\n'.format(numb, foo))
10 Bar
>>>

但是在2.6中,我遇到了ValueError异常.

But in 2.6 I get a ValueError exception.

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.6

When looking through the documentation (2.6, 2.7), I can see no mention of changes having been done between the two versions. What is happening here?

推荐答案

Python 2.6和更低版本(以及Python 3.0)要求,您需要为占位符编号:

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

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

如果在python 2.7和python 3.1及更高版本中省略了编号,则该编号是隐式的,请参见

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

在2.7版中已更改:可以省略位置参数说明符,因此'{} {}'等效于'{0} {1}'.

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

隐式编号很流行; Stack Overflow上的许多示例都使用它,因为这样更容易生成快速格式化字符串.我忘了在必须仍支持2.6的项目中多次包含它们.

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.

这篇关于适用于Python 2.6的Str.format()给出了错误,其中2.7没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆