Python 3:使用 %s 和 .format() [英] Python 3: using %s and .format()

查看:32
本文介绍了Python 3:使用 %s 和 .format()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于在我的 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() 通常应该使用.

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所说这句话已从 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.

Python 3.4 第 7.1.1 段开始 读:

% 运算符也可用于字符串格式化.它解释左参数很像 sprintf() 样式的格式字符串应用于正确的参数,并返回产生的字符串这个格式化操作.

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.4 4.7.2 printf 风格的字符串格式.

这篇关于Python 3:使用 %s 和 .format()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆