Python 3 : using %s and . 格式()

标签 python string string-formatting

我终于在我的 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.4 4.7.2 printf-style String Formatting.

关于Python 3 : using %s and . 格式(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14753844/

相关文章:

Python程序连续将辅音移动到字符串的末尾,直到第一个字母是元音

c++ - 在 native C++ 类中缓存字符串长度的后果?

java - 在java中的字符串中附加值

python - 将 python 字典的最坏情况时间复杂度优化为 O(1)

python Pandas : concatenate rows with unique values

java - JOptionPane.showInputDialog 问题

java - 如何在 Java 中将数字格式化为固定长度、空格填充、千位分隔符、2 位小数

java - 遇到变量无法打印和\n 无法工作的问题

python - 在 Dask 中高效删除行

python - numpy - 对数组的每一行应用聚合