Python 3:使用%s和.format()

时间:2013-02-07 14:45:25

标签: python string string-formatting

我最终在2.x代码中从%切换到.format()字符串格式化运算符,以便将来更容易迁移到3.x.有一点令人惊讶的是,不仅% - 样式格式保留在Py3中,而且它在标准库代码中被广泛使用。这似乎是合乎逻辑的,因为写'(%s)' % variable'({})'.format(variable)更短,更容易理解。但我仍有疑问。在代码中使用这两种方法是否合适(pythonic?)? 谢谢。

2 个答案:

答案 0 :(得分:24)

Python 3.2文档说,%最终会消失。

http://docs.python.org/3.2/tutorial/inputoutput.html#old-string-formatting

  

由于str.format()很新,很多Python代码仍使用%   运营商。但是,因为这种旧的格式化方式会   最终会从语言中移除str.format()   使用。

但是@regilero says句子从3.3 消失,这可能表明事实并非如此。有一些对话here表明了同样的事情。

Python 3.4 the paragraph 7.1.1开始:

  

%运算符也可用于字符串格式化。它解释   左边的参数很像sprintf() - 样式格式字符串   应用于右参数,并返回由此产生的字符串   这种格式化操作。

另见Python 3.4 4.7.2 printf-style String Formatting.

答案 1 :(得分:-2)

“%s”现在是“{}”,因此添加%s时将其替换为{},您希望将变量添加到字符串中。

def main():
    n="Python 3.+" 
    l="looks nice"
    f="does not look practical."


    print("This seems to be the new way {}".format(n)\
      + "will be working, rather than the ' % ',{} but {}".format(l,f))



main()

#In comparison to just injecting the variable

出于说明原因,输出忽略了它们的引用

“这似乎是新方式”Python 3. +“ 将工作,而不是'%;,“看起来不错”但“看起来不实用。”“