【问题标题】:Str.format() for Python 2.6 gives error where 2.7 does notPython 2.6 的 Str.format() 给出了 2.7 没有的错误
【发布时间】:2013-11-09 05:00:22
【问题描述】:

我有一些在 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),我看不到两个版本之间的更改。这里发生了什么?

【问题讨论】:

    标签: python python-2.7 string-formatting python-2.6 backwards-compatibility


    【解决方案1】:

    Python 2.6 及之前版本(以及 Python 3.0)要求您为占位符编号:

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

    如果在 Python 2.7 和 Python 3.1 及更高版本中省略,编号是隐式的,请参阅documentation

    2.7 版更改:位置参数说明符可以省略,所以'{} {}' 等价于'{0} {1}'

    隐式编号很流行; Stack Overflow 上的很多示例都使用它,因为这样更容易快速创建格式字符串。在处理仍必须支持 2.6 的项目时,我忘记多次包含它们。

    【讨论】:

    • 谢谢。我正忙着看方法本身的文档,我一开始就错过了文本。
    【解决方案2】:

    这在此处的文档中:
    http://docs.python.org/2/library/string.html#format-string-syntax

    该部分大约进行到一半:

    2.7 版更改:位置参数说明符可以省略,所以'{} {}' 等价于'{0} {1}'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-18
      • 2010-12-24
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多