typeerror:格式字符串PYTHON没有足够的参数

时间:2015-04-16 02:16:46

标签: python string

我正在学习python 2.7.8。我不知道什么是错的,我已经尝试了所有的答案。这是代码:

formatterb = "%r %r %r %r"
print formatterb % (
    "I am tired", 
    "Not so tired tho"
    "this had better work.", 
    "been at this for a while")

这是'我得到的错误信息:

TypeError: not enough arguments for format strings.

1 个答案:

答案 0 :(得分:6)

您在"Not so tired tho" "this had better work."之间缺少逗号,因此没有足够的参数。

应该是:

formatterb = "%r %r %r %r"
print formatterb % (
    "I am tired", 
    "Not so tired tho",
    "this had better work.", 
    "been at this for a while")

根据OP的评论进行编辑:

字符串中不能有4个格式说明符,但附带的元组中只有3个元素。如果您希望第二个和第三个参数位于同一行,则它们应该是相同的参数,即"Not so tired tho this had better work"

如果您想在不同的行上创建项目,通常可以添加换行符,例如:

formatterb = "%r %r %r"
print formatterb % (
    "I am tired", 
    "Not so tired tho\nthis had better work.", 
    "been at this for a while")

\n将在两个子字符串之间添加换行符。在任何一种情况下,您都希望删除其中一个格式说明符。

但是,请注意%r相当于repr,因此您将看到实际的字符串内容,而不是打印的内容。例如即使使用换行符,您也会看到\n而不是实际换行符。

如果您将%r替换为%s,它会显示如何打印,您会看到它的输出如下:

I am tired Not so tired tho
this had better work. been at this for a while