To answer your first question... .format
just seems more sophisticated in many ways.
(要回答您的第一个问题... .format
在许多方面似乎都更加复杂。)
An annoying thing about %
is also how it can either take a variable or a tuple. (关于%
一个烦人的事情是它如何可以接受变量或元组。)
You'd think the following would always work: (您会认为以下各项将始终有效:)
"hi there %s" % name
yet, if name
happens to be (1, 2, 3)
, it will throw a TypeError
.
(但是,如果name
恰好是(1, 2, 3)
,它将抛出TypeError
。)
To guarantee that it always prints, you'd need to do (为了确保它始终打印,您需要执行)
"hi there %s" % (name,) # supply the single argument as a single-item tuple
which is just ugly.
(真丑。)
.format
doesn't have those issues. (.format
没有那些问题。)
Also in the second example you gave, the .format
example is much cleaner looking. (同样在您给出的第二个示例中, .format
示例看起来更.format
。)
Why would you not use it?
(为什么不使用它?)
- not knowing about it (me before reading this)
(不知道(我在阅读本文之前))
- having to be compatible with Python 2.5
(必须与Python 2.5兼容)
To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated.
(为了回答您的第二个问题,字符串格式化与其他任何操作都同时发生-计算字符串格式化表达式时。)
And Python, not being a lazy language, evaluates expressions before calling functions, so in your log.debug
example, the expression "some debug info: %s"%some_info
will first evaluate to, eg "some debug info: roflcopters are active"
, then that string will be passed to log.debug()
. (而且,Python不是一种惰性语言,它会在调用函数之前先评估表达式,因此在您的log.debug
示例中,表达式"some debug info: %s"%some_info
首先会评估为例如"some debug info: roflcopters are active"
,那么该字符串将传递给log.debug()
。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…