ValueError:python格式的零长度字段名

2024-04-19 19:39:24 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
“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.

代码是用Python2.6或2.7编写的,但我运行Python3.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()

谢谢你的帮助。


Tags: nameinformatfieldoutputdeferrorlength
1条回答
网友
1楼 · 发布于 2024-04-19 19:39:24

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

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

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

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

相关问题 更多 >