【问题标题】:Python TypeError: not enough arguments for format string in case of string %sPython TypeError:在字符串 %s 的情况下,格式字符串的参数不足
【发布时间】:2017-01-19 11:04:57
【问题描述】:
wrapper = """<html>
<head>
</head>
<body>
<table style="height: 100px;" width="500">
<tbody>
<tr>
<td rowspan="3"><a id="imgrec1" href="http://www.w3.org"><img src="%s" alt="Smiley face" width="50" height="100" /><br /><br /></a></td>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<tr>
<td rowspan="3"><a id="imgrec1" href="http://www.w3.org"><img src="%s" alt="Smiley face" width="50" height="100" /><br /><br /></a></td>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
<td>%s</td>
</tr>
<tr>
</tbody>
</table>
</body>
</html>"""

str=""
for i in reclist[:2]: 
    str=str + "I[\"" + i + "\"]," + "T[\"" + i + "\"]," +"R[\"" + i + "\"]," +"P[\"" + i + "\"]," 
str = str[:-1]
print str
whole = wrapper % (str)

Output: I["M1"],T["M1"],R["M1"],P["M1"],I["M2"],T["M2"],R["M2"],P["M2"]
    whole = wrapper % (str)
    TypeError: not enough arguments for format string

wrapper 正好有 8 个 %s,str 也有 8 个元组,但仍然显示错误 TypeError: not enough arguments for format string.

但是如果我使用

而不是 str
    whole = wrapper %  
(I["M1"],T["M1"],R["M1"],P["M1"],I["M2"],T["M2"],R["M2"],P["M2"])

然后它工作正常。

我向stackoverflow stackoverflow 咨询了这个问题,但没有帮助。

【问题讨论】:

  • 请发布一个简单的wrapper = "..."; str = ...; output = wrapper % str 示例。

标签: python html string typeerror


【解决方案1】:

我想你得到一个错误是因为你在格式化字符串时将字符串作为单个参数传递。 您可以先创建一个列表:

str = []
for i in reclist[:2]:
    str += [I[i], T[i] etc.]

然后使用:

whole = wrapper % tuple(str)

这样列表中的每个项目都将作为单独的参数传递。

【讨论】:

  • 谢谢。这个程序的输出现在是 ['I', '[', '"', 'M', '"', ']', ',', 'T', '[', '"', 'M'等] Traceback(最近一次调用最后一次):whole = wrapper % tuple(str) TypeError: not all arguments convert during string formatting
  • 什么是 I、T、R、P 变量?它们是字典吗?
  • 尝试创建不带引号的列表。 [I[i], T[i]] 而不是 ['I','[', i , ']', 'T', '[', i, ']'] 或类似的东西。
  • 是的。 I,R,T,P 是字典。
  • 那我不知道。你能再次发布for循环吗?可能您创建了一个包含比需要更多参数的列表。
猜你喜欢
  • 2012-06-24
  • 2014-08-06
  • 2018-02-02
  • 2018-06-07
  • 1970-01-01
  • 2020-10-17
  • 2012-06-11
  • 2019-01-17
相关资源
最近更新 更多