繁体   English   中英

python中的formatter

[英]formatter in 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, formatter)
print formatter % (
    "I had this thing.",
    "That you could type up right.",
    "But it didn't sing.",
    "So I said goodnight."
)

作者没有解释每个“打印”后“格式化程序”正在做什么。 如果我删除它们,所有内容都会完全相同。 我在这里错过了什么吗?

不,它不会打印完全相同的东西。 如果您使用formatter % part,则没有逗号,也没有括号。

如果扩展格式化程序会更清楚。 我建议你使用:

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

代替。

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

formatter是一个字符串。 所以,第一行与以下相同:

"%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 (在你的例子中,我认为strrepr为所有这些对象返回相同的内容,因此如果你将formatter更改为使用%s而不是%r ,输出将完全相同)

这是字符串格式化的经典格式, print "%r" % var将打印print "%r" % var的原始值,4%r期望在%之后传递4个变量。

一个更好的例子是:

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)

print "my name is {name} I'm a {profession}".format(name="sherlock holmes", profession="detective")

更多信息:

http://www.python.org/dev/peps/pep-3101/

http://pythonadventures.wordpress.com/2011/04/04/new-string-formatting-syntax/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM