数值错误:无法从手动字段规范切换到自动字段编号。

51

这个类:

class Book(object):
    def __init__(self, title, author):
        self.title = title
        self.author = author

    def get_entry(self):
        return "{0} by {1} on {}".format(self.title, self.author, self.press)

从中创建一个我的书的实例:

In [72]: mybook = Book('HTML','Lee')
In [75]: mybook.title
Out[75]: 'HTML'
In [76]: mybook.author
Out[76]: 'Lee'
请注意,我在get_entry方法中使用了属性'self.press',但我没有对其进行初始化。请继续输入数据。
mybook.press = 'Murach'
mybook.price = 'download'

到目前为止,我可以使用vars指定所有数据输入。

In [77]: vars(mybook)
Out[77]: {'author': 'Lee', 'title': 'HTML',...}

我在控制台中输入了很多关于我的书籍的数据。当尝试调用get_entry方法时,出现了错误报告。

mybook.get_entry()
ValueError: cannot switch from manual field specification to automatic field numbering.

在控制台上以交互模式进行所有操作。我珍视输入的数据,进一步将mybook对象保存到文件中。然而,它有缺陷。如何在交互模式下挽救它,否则我必须重新开始。

4个回答

63
return "{0} by {1} on {}".format(self.title, self.author, self.press)

那样行不通。如果你要指定位置,必须一直到末尾:

return "{0} by {1} on {2}".format(self.title, self.author, self.press)

在您的情况下,最好让Python自动处理:

return "{} by {} on {}".format(self.title, self.author, self.press)

2
print ("{0:.1f} and the other no {0:.2f}".format(a,b)) 

在代码的单次执行中,Python 无法同时进行手动和自动精度处理(字段编号)。您可以为每个变量指定字段编号,也可以让 Python 自动为所有变量进行编号。


1
这里使用了变量 b 吗? - Jean-François Fabre

1
如果使用 f"" 格式而不是 format,就可以以表格格式提供适当的输出。
例如:
<!DOCTYPE html>
<html>
<head>
    <title><strong>Unable to handle Value Error</strong></title>
</head>
<body>
<p><ol>for name, branch,year in college:</ol>
         <ol> print(f"{name:{10}} {branch:{20}} {year:{12}} )</ol>
    
    <ol>name       branch               year    </ol>
    <ol>ankit      cse                         2</ol>
    <ol>vijay      ece                         4</ol>
<ol>    raj        IT                          1</ol>

</body>
</html>

0

转义特殊字符 例如:'{}' -> '{{}}'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接