我终于在我的 2.x 代码中从 %
切换到 .format()
字符串格式化运算符,以便更容易迁移到 3.x在未来。令人惊讶的是,不仅 %
样式的格式保留在 Py3 中,而且在标准库代码中被广泛使用。这似乎是合乎逻辑的,因为编写 '(%s)' % variable
比 '({})'.format(variable)
要短一些,而且可能更容易理解。但我仍然有疑问。在代码中使用这两种方法是否合适(pythonic?)?
谢谢。
最佳答案
Python 3.2 文档说,%
最终会消失。
http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting
Since
str.format()
is quite new, a lot of Python code still uses the%
operator. However, because this old style of formatting will eventually be removed from the language,str.format()
should generally be used.
但是作为 @regilero says , 这句话从 3.3 中消失了,这可能表明情况并非如此。有一些对话here这暗示了同样的事情。
截至 Python 3.4 the paragraph 7.1.1阅读:
The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation.
关于Python 3 : using %s and . 格式(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753844/