2017-05-16 66 views
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 
+0

尝试:'打印( “值(MEM%d)” %(I))'....没有'+' – depperm

+2

这不回答你的问题,但你不应该使用Python的内置的字符串格式来组合sql语句。无论你用什么库来执行sql,都会有一个特性让你插入变量而不会有sql注入攻击的危险。 – Kevin

+0

尝试'print(“values(Mem%d)”%(i))' – kuro

回答

4

问题是你如何使用%

正在更换的%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 
2

你可以这样做更多simplier如果转换成INT像这样的字符串:

i = 0 
while (i<= 10): 
    print("insert into Member " + "(Mem_ID)") 
    print("values " + "(" + "Mem" + str(i) + ")") 
    i = i+1 
+1

你有相同的缩进问题,如OP – kuro

+0

确保在回答问题时使用适当的缩进。 –

+0

@kuro我的巨大的坏,非常感谢! –