Python 上的 IndexError 超出范围
我有一个 python 代码将数据插入到我的数据库中。这是该行: query = '插入 1_recipe 值({0})'
。我使用 {0}
传递 CSV 文件中的所有数据。在我的代码中使用 sys.argv 之前它工作得很好。这是新代码:
import sys
nomor = sys.argv[1]
.....
query = "insert into {idnumber}_recipe values ({0})".format(idnumber = nomor)
query = query.format(','.join(['%s'] * len(data)))
.....
当我运行此代码时,总是返回此错误:
'query = "insert into {idnumber}_recipe values ({0})".format(idnumber = nomor)
IndexError: Replacement index 0 out of range for positional args tuple'
如何修复它?谢谢。
更新: 我已经找到答案了。谢谢
I have a python code to insert data into my database. Here is the line:query = 'insert into 1_recipe values({0})'
. I used {0}
to pass all data from my CSV file. It works perfectly before I use sys.argv
in my code. Here is the new code :
import sys
nomor = sys.argv[1]
.....
query = "insert into {idnumber}_recipe values ({0})".format(idnumber = nomor)
query = query.format(','.join(['%s'] * len(data)))
.....
When I run this code, always back with this error :
'query = "insert into {idnumber}_recipe values ({0})".format(idnumber = nomor)
IndexError: Replacement index 0 out of range for positional args tuple'
How to fix it? Thanks.
Update:
I already found the answer. Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仅向
format()
函数传递一个参数:format 函数没有可赋予格式化字符串的
({0})
部分的值。提供另一个值或更改它,以便它也将使用
idnumber
You are only passing one argument to the
format()
function:The format function doesn't have a value to give to the
({0})
part of the formatted string.Either give another value or change it so it will use
idnumber
as well您可以查看格式化查询开发 在这里。
例如:
您的代码可以使用更好的格式重写,如下所示:
注意:此代码仅根据给出的示例显示更好的格式。由于语法不正确,此查询可能会也可能不会按预期运行。
You can look at query development for formatting here.
e.g.:
Your code can be rewritten something like this using better formatting:
Note: This code is showing only better formatting as per the example given. This query may or may not run as expected due to incorrect syntax.