【问题标题】:TypeError when using format string [duplicate]使用格式字符串时出现 TypeError [重复]
【发布时间】:2015-04-15 14:28:20
【问题描述】:

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

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

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

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

【问题讨论】:

  • 我认为您的搜索方式不正确。只需将错误消息放入 google 即可提供许多 SO 答案,前三个中的每一个都解释了问题。
  • 让您的问题更简短。最好是在你转储所有代码之前。

标签: python


【解决方案1】:

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

'%s %s' % a, b

它的解析方式类似(但不精确)

('%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)

【讨论】:

    【解决方案2】:

    print 语句必须是

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

    【讨论】:

    • 我有点困惑,所以在那一行我确实需要这样使用: print("'%s' 在他的第一个位置雇用了 '%s' 作为部队。" % (name , slot1)) 但是在其他行我使用这样的代码,并没有出现错误: print("Slots left: %s" % slotamount) 有什么区别,什么时候使用?
    • @LeDirt 当你有一个变量时,你不需要使用元组,只要有多个,你需要把它们放在一个元组中。
    猜你喜欢
    • 2016-05-22
    • 2014-09-05
    • 2021-12-17
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 2015-07-14
    相关资源
    最近更新 更多