前几天遇到tuple索引号越界的报错,调试了好久都没解决,幸亏柳老师帮我分析后搞定啦,感激~在这里记录一下
背景
代码用 python 抓取网站信息的数据,导入本地数据库(MySQL)时 遇到下标越界问题
```python
IndexError: Replacement index 12 out of range for positional args tuple
虽然是在format这行报的错,但实际错的是上面values的
位置参数的{0}就表示format函数中的第一个值,依次类推。
format里面就11个值,所以调用它的对象里的索引最多到{10} ,即下面所示
sqlstr += "values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')"
再次运行后很开心,这个bug解决啦
我之前以为要跟字典里结构的位置相匹配,就改成 {12} {16} {17} 了,哇咔咔,我的错
真就是基础不牢,地动山摇,要系统地学一下python噢
python的 self参数 就像 java 里的 this 哈
代码优化
柳老师还顺便帮我优化了一下代码,嘿嘿嘿
sqlstr = "insert into fy_successors (name,sex,cover_pic,details,updated_at,created_at,province,project,born_year,cate,batch)"
sqlstr += "values({1},{2},{3},{4},{6},{7},{9},{12},{14},{16},{17})"
sqlstr.format("'"+dict_successor['name']+"'","'"+dict_successor['sex']+"'","'"+dict_successor['cover_pic']+"'","'"+pymysql.escape_string(dict_successor['details'])+"'","'"+dict_successor['updated_at']+"'","'"+dict_successor['created_at']+"'","'"+dict_successor['province']+"'","'"+dict_successor['project']+"'","'"+dict_successor['born_year']+"'","'"+dict_successor['cate']+"'","'"+dict_successor['batch']+"'")
这样写的可读性很低,要把引号放在位置参数两边,更简洁 ‘{ 1 }’
修改后:
sqlstr = "insert into fy_successors (name,sex,cover_pic,details,updated_at,created_at,province,project,born_year,cate,batch)"
sqlstr += "values('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')"
sqlstr.format(dict_successor['name'],dict_successor['sex'],dict_successor['cover_pic'],pymysql.escape_string(dict_successor['details']),dict_successor['updated_at'],dict_successor['created_at'],dict_successor['province'],dict_successor['project'],dict_successor['born_year'],dict_successor['cate'],dict_successor['batch'])
怎么样,是不是简洁很多呀