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

mal*_*nis 60 python format

可能重复:
Python 3.0,3.1,3.2中的"ValueError:格式为零长度字段名称"错误

我花了好几个小时试图解决这个问题,但无济于事.我读了这本指南.我没有找到如何做我需要的任何例子.

当我运行脚本时,我收到此错误(部分省略):

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

代码是用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()
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

phi*_*hag 149

有可能你正在运行一个旧的Python版本,而不是3.1.在Python 2.6中,您需要格式规格的索引,如下所示:

"{0} {1}\n".format(x,y)
Run Code Online (Sandbox Code Playgroud)

将Python版本更新为最近的版本,最好是2.7或3.2,以解决问题.根据文档,省略数字索引应该在Python 3.1中工作:

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