Python 的打印方式: 用“格式”还是百分比形式?

在 Python 中,生成格式化输出似乎有两种不同的方式:

user = "Alex"
number = 38746
print("%s asked %d questions on stackoverflow.com" % (user, number))
print("{0} asked {1} questions on stackoverflow.com".format(user, number))

有没有一种方法比另一种更受欢迎?它们是等价的吗,有什么区别吗?应该使用什么形式,尤其是 Python 3?

87736 次浏览

Use the format method, especially if you're concerned about Python 3 and the future. From the documentation:

The formatting operations described here are modelled on C's printf() syntax. They only support formatting of certain builtin types. The use of a binary operator means that care may be needed in order to format tuples and dictionaries correctly. As the new :ref:string-formatting syntax is more flexible and handles tuples and dictionaries naturally, it is recommended for new code. However, there are no current plans to deprecate printf-style formatting.

The docs say that the format method is preferred for new code. There are currently no plans to remove % formatting, though.

.format was introduced in Python2.6

If you need backward compatibility with earlier Python, you should use %

For Python3 and newer you should use .format for sure

.format is more powerful than %. Porting % to .format is easy but the other way round can be non trivial

You can use both .No one said % formatting expression is deprecated.However,as stated before the format method call is a tad more powerful. Also note that the % expressions are bit more concise and easier to code.Try them and see what suits you best