使用格式字符串时的TypeError

时间:2015-02-14 17:45:18

标签: python

注意:我在这个网站上搜索了一个答案,但他们都没有帮助我。

**TypeError: not enough arguments for format string**

嗨,这是我学习python的第一个小时。我决定尝试我已经知道的并写了一个代码,但是这行出错:

print("'%s' hired '%s' as troop in his first slot." % name, slot1)

2 个答案:

答案 0 :(得分:3)

你必须为字符串提供一个元组参数,否则它只会采取第一件事。当你有:

'%s %s' % a, b

它的解析类似(但不是exaclty),如

('%s %s' % a), b

表示b不是%运算符的参数的一部分。要解决此问题,请将ab加上括号以代替单个元组参数

'%s %s' % (a, b)

根据您的具体情况

"'%s' hired '%s' as troop in his first slot." % (name, slot1)

虽然您可能想要考虑较新的python format语法

"'{}' hired '{}' as troop in his first slot.".format(name, slot1)

答案 1 :(得分:1)

print语句必须是

print("'%s' hired '%s' as troop in his first slot." % (name, slot1))