【问题标题】:ValueError: zero length field name in format python [duplicate]ValueError:python格式的零长度字段名称[重复]
【发布时间】:2012-04-07 11:38:40
【问题描述】:

可能重复:
“ValueError: zero length field name in format” error in Python 3.0,3.1,3.2

我花了几个小时试图解决这个问题,但无济于事。我读了this guide。 我还没有找到任何示例如何做我需要的。

运行脚本时出现此错误(部分省略):

Traceback (...):
   [...]
   output.write("{: > 026,.18e} {: > 026,.18e}\n".format(x,y))
ValueError: zero length field name in format.

代码是用 python 2.6 或 2.7 编写的,但我运行的是 python 3.1。我需要如何更改输出格式才能正常工作?

def f(x,y,a = 0.01):
    return y/(a+x)-y**3

def ekspEuler(N,dat):
    output = open(dat,"w")
    h = 3.0/N
    x,y = 0,1 #zac.pogoj

    for i in range(1,N+2):
        output.write("{: > 026,.18e} {: > 026,.18e}\n".format(x,y))
        y += h*f(x,y)
        x = i*h
    output.close()

感谢您的帮助。

【问题讨论】:

  • 好吧,你想做什么?或者换个方式问,你为什么不想要"{}{}".format(x,y)
  • 是一个括号里有两个说明符的问题吗?我省略了 .18e,然后我得到了 OverflowError:(34, 'Numerical result our of range')

标签: python format


【解决方案1】:

您运行的可能是旧版 Python,而不是 3.1。在 Python 2.6 中,您需要格式规范中的索引,如下所示:

"{0} {1}\n".format(x,y)

将您的 Python 版本更新到最新版本,最好是 2.7 或 3.2,以解决问题。根据文档,省略数字索引should work in Python 3.1

3.1 版更改:位置参数说明符可以省略,因此“{} {}”等效于“{0} {1}”。

【讨论】:

  • 我正在运行 python 3.1.3,我正在使用 Geanny。我不知道如何安装3.2版本。我是 linux 新手。
  • 抱歉,我不知道 Geanny 是什么。你的意思是编辑Geany?在任何情况下,您都可以通过import sys;print(sys.version) 找到您的 Python 版本。 Linux 发行版有很多,你用的是哪一个?
  • 是 Geany。我正在使用 Ubuntu 10.04。你是对的。我正在使用 2.6.5。我试过这个: output.write("{0: > 026,.18e} {1: > 026,.18e}\n".format(x,y)) 我得到 ValueError:Invalid conversion specification
  • 在当前Ubuntu 11.10, Python 2.7 is the default。所以你可以更新你的 Ubuntu 安装——无论如何我不会向初学者推荐一个旧的。或者,在您的系统上使用install a newer Python,或者通过使用#!/usr/bin/env python3.1 启动您的程序在Python3 下运行。
  • 我有 11.10 但我不喜欢它。接下来我将搬到 linux mint。现在它运行 3.1.2 并且该错误不再出现。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多