问题描述
我终于在我的 2.x 代码中从 %
切换到 .format()
字符串格式化操作符,以便更容易迁移到 3.x在未来.发现不仅 %
样式的格式保留在 Py3 中,而且它在标准库代码中被广泛使用,这有点令人惊讶.这似乎是合乎逻辑的,因为编写 '(%s)' % variable
比 '({})'.format(variable)
更短,而且可能更容易理解.但我仍然怀疑.在代码中使用这两种方法是否合适(pythonic?)?谢谢.
I have finally switched from %
to the .format()
string formatting operator in my 2.x code in order to make it easier to migrate to 3.x in future. It was a bit surprising to find out that not only the %
-style formatting remains in Py3, but it is widely used in the standard library code. It seems logical, because writing '(%s)' % variable
is a bit shorter and maybe easier to comprehend than '({})'.format(variable)
. But I'm still in doubt. Is it proper (pythonic?) to use both approaches in the code? Thank you.
推荐答案
Python 3.2 文档说,%
最终会消失.
Python 3.2 documentation said that, %
will eventually go away.
http://docs.python.org/3.2/教程/inputoutput.html#old-string-formatting
由于 str.format()
比较新,很多 Python 代码仍然使用 %
操作员.但是,因为这种旧的格式样式会最终从语言中删除,str.format()
通常应该使用.
但正如@regilero所说,这句话已从 3.3 消失,这可能表明实际情况并非如此.有一些对话这里 暗示同样的事情.
But as @regilero says, the sentence is gone from 3.3, which might suggest it's not actually the case. There are some conversations here that suggest the same thing.
% 运算符也可用于字符串格式化.它解释左参数很像 sprintf() 样式的格式字符串应用于正确的参数,并返回产生的字符串这个格式化操作.
另见 Python 3.4 4.7.2 printf 风格的字符串格式.
这篇关于Python 3:使用 %s 和 .format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!