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

y2k*_*y2k 125 python string format typeerror

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

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname, procversion, int(percent), exe, description, company, procurl
Run Code Online (Sandbox Code Playgroud)

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

7虽然7?

And*_*ark 226

您需要将格式参数放入元组(添加括号):

instr = "'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % (softname, procversion, int(percent), exe, description, company, procurl)
Run Code Online (Sandbox Code Playgroud)

您目前拥有的内容相当于以下内容:

intstr = ("'%s', '%s', '%d', '%s', '%s', '%s', '%s'" % softname), procversion, int(percent), exe, description, company, procurl
Run Code Online (Sandbox Code Playgroud)

例:

>>> "%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'
Run Code Online (Sandbox Code Playgroud)

  • 那工作了很多.我试图使用%s格式来避免NoneType错误,但我仍然得到它.相关:http://stackoverflow.com/questions/1338690/good-way-of-handling-nonetype-objects-when-printing-in-python (3认同)

Sim*_*ser 155

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

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

这也解决了您碰巧遇到的错误.

  • @SimeonVisser,为什么这会变得过时?例如,如果您使用一个变量来存储格式字符串,并且您希望将带有替换值的字符串放在同一个变量中,那么您只需使用**format_string%=('bla','bla','bla' ")**.注意详细说明或指出一些有用的链接? (4认同)

小智 13

在格式字符串中使用%作为百分比字符时出现相同的错误.解决方法是将%%加倍.

  • 提供一些代码示例,说明您的解决方案如何工作,以及如何在没有它的情况下失败等等可能会有用.请参阅[如何写出一个好的答案?](https://stackoverflow.com/help/how-to-answer).请注意,这是一个有5年历史的问题,因此,只有当答案提供的信息明显多于已存在的信息时,才应添加答案. (3认同)