Python 字符串格式化format和%的比较

Python string formatting: % vs. .format

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

Python format 和百分号 %的比较

To answer your first question…

.format

just seems more sophisticated in many ways. 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 a list: (1, 2, 3)

, it will throw a

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. Also in the second example you gave, the .format

example is much cleaner looking.
Why would you not use it?

什么时候下使用format或%

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, e.g.

"some debug info: roflcopters are active"

, then that string will be passed to

log.debug()

原文链接:https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format

发表评论

电子邮件地址不会被公开。 必填项已用*标注

− 3 = 2