Python TypeError: 格式化字符串的参数不足

这是输出。这些是 utf-8字符串,我相信... 其中一些可以是 NoneType 但它立即失败,在那样的之前..。

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl

TypeError: 格式化字符串的参数不足

不过7比7呢?

330078 次浏览

您需要将格式参数放入一个 tuple 中(添加括号) :

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)

你目前所拥有的相当于以下数据:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl

例如:

>>> "%s %s" % 'hello', 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % ('hello', 'world')
'hello world'

请注意,用于格式化字符串的 %语法已经过时。如果你的 Python 版本支持它,你应该写:

instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)

这还修复了您碰巧遇到的错误。

当在格式字符串中使用 %作为百分比字符时,我得到了相同的错误。解决这个问题的方法是将 %%翻倍。

我有同样的问题,我使用 生的查询的一个特定的原因,这是添加双引号在 TIME _ FORMAT 函数。

User.objects.raw(
f'SELECT f1,f2,TIME_FORMAT(SEC_TO_TIME(SUM(TIME_TO_SEC(end_time) - TIME_TO_SEC(start_time))),"%%H:%%i") AS log FROM users GROUP BY start_dt')