python中的格式化程序

python中的格式化程序,python,Python,我正在阅读一本python书籍中的练习,我对这段代码中发生的事情感到有点困惑 formatter = "%r %r %r %r" print formatter % (1, 2, 3, 4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, False, True) print formatter % (formatter, formatter, formatter, format

我正在阅读一本python书籍中的练习,我对这段代码中发生的事情感到有点困惑

formatter = "%r %r %r %r"

print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
)

作者没有解释“格式化程序”在每次“打印”后都在做什么。如果我去掉它们,所有的打印结果都是一样的。我这里漏了什么吗?

不,它没有打印出完全相同的内容。如果使用
formatter%
部分,则没有逗号和括号

如果您扩展格式化程序,它会更清晰。我建议您使用:

formatter = "One: %r, Two: %r, Three: %r, Four: %r"
相反


格式化程序充当模板,每个
%r
充当右侧元组中值的占位符。

格式化程序是一个字符串。因此,第一行与:

"%r %r %r %r" % (1, 2, 3, 4)
它对右侧元组中的每个项调用
repr
,并用结果替换相应的
%r
。当然,它也会为你做同样的事情

formatter % ("one", "two", "three", "four")
等等

请注意,您还会经常看到:

"%s %s %s %s" % (1, 2, 3, 4)

它调用
str
而不是
repr
。(在您的示例中,我认为
str
repr
为所有这些对象返回相同的内容,因此如果将
formatter
更改为使用
%s
而不是
%r
),则输出将完全相同。

这是字符串格式的经典格式,
打印“%r”%var
将打印var的原始值,四个%r希望在%之后传递四个变量

更好的例子是:

formatter = "first var is %r, second is %r, third is %r and last is %r"
print formatter % (var1, var2, var3, var4)
使用formatter变量只是为了避免在打印中使用长行,但通常不需要这样做

print "my name is %s" % name
print "the item %i is $%.2f" % (itemid, price)
%.2f
是浮点数,逗号后有2个值

您可能希望尝试一种新的字符串格式:(如果您至少使用2.6)

更多信息,请访问:


如果我只取出“格式化程序”,将%保留在中,则完全相同。我知道如果没有它,情况会完全不同。但我对“格式化程序”特别好奇。@user1641994:编辑你的问题,以显示打印相同内容的代码。我可以向您保证,
print%(1,2,3,4)
不是有效的Python语法。是的,您是对的。我以前把它存起来的时候搞砸了。谢谢
print "my name is {name} I'm a {profession}".format(name="sherlock holmes", profession="detective")