我试图将字符串和数字与字符串格式化格式,但我得到一个错误字符串拼接
"TypeError: not all arguments converted during string formatting"
这是我的代码
i = 0
while (i<= 10):
print("insert into Member" + "(Mem_ID)")
print("values" + "(" + "Mem%d" + ")" %(i))
i = i+1
我试图将字符串和数字与字符串格式化格式,但我得到一个错误字符串拼接
"TypeError: not all arguments converted during string formatting"
这是我的代码
i = 0
while (i<= 10):
print("insert into Member" + "(Mem_ID)")
print("values" + "(" + "Mem%d" + ")" %(i))
i = i+1
问题是你如何使用%
正在更换的%d
应在报价旁边应有%(var)
。
i = 0
while (i<= 10):
print("insert into Member " + "(Mem_ID)")
print("values " + "(" + "Mem%d"%(i) + ")")
i += 1
请记住,您应该使用.format()
作为当前的方法。
i = 0
while (i<= 10):
print("insert into Member " + "(Mem_ID)")
print("values " + "(" + "Mem{}".format(i) + ")")
i += 1
另外要清楚一些你的报价是不需要的。你也可以使用它。
i = 0
while (i<= 10):
print("insert into Member (Mem_ID)")
print("values (Mem{})".format(i))
i += 1
你可以这样做更多simplier如果转换成INT像这样的字符串:
i = 0
while (i<= 10):
print("insert into Member " + "(Mem_ID)")
print("values " + "(" + "Mem" + str(i) + ")")
i = i+1
尝试:'打印( “值(MEM%d)” %(I))'....没有'+' – depperm
这不回答你的问题,但你不应该使用Python的内置的字符串格式来组合sql语句。无论你用什么库来执行sql,都会有一个特性让你插入变量而不会有sql注入攻击的危险。 – Kevin
尝试'print(“values(Mem%d)”%(i))' – kuro