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

2024-04-26 00:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

这是输出。我相信这些是utf-8字符串。。。其中一些可能是非类型的,但它会立即失败,在那些之前。。。

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

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

7比7?


Tags: 字符串类型参数格式descriptionexecompanyutf
3条回答

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

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)

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

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

相关问题 更多 >