Python 至少有六种格式化字符串的方法:
In [1]: world = "Earth"
# method 1a
In [2]: "Hello, %s" % world
Out[2]: 'Hello, Earth'
# method 1b
In [3]: "Hello, %(planet)s" % {"planet": world}
Out[3]: 'Hello, Earth'
# method 2a
In [4]: "Hello, {0}".format(world)
Out[4]: 'Hello, Earth'
# method 2b
In [5]: "Hello, {planet}".format(planet=world)
Out[5]: 'Hello, Earth'
# method 2c
In [6]: f"Hello, {world}"
Out[6]: 'Hello, Earth'
In [7]: from string import Template
# method 3
In [8]: Template("Hello, $planet").substitute(planet=world)
Out[8]: 'Hello, Earth'
不同方法的简史:
printf
样式的格式从 Python 婴儿期就已经存在Template
类是在 Python 2.4 中引入的format
方法是在 Python 2.6 中引入的f
-字符串是在 Python 3.6 中引入的
我的问题是:
printf
样式的格式是否已弃用或将要弃用?- 在
Template 类
中,substitute
方法是弃用还是将要弃用? (我不是在谈论safe_substitute
,据我了解,它提供了独特的功能)
类似的问题以及为什么我认为它们不是重复的:
Python string formatting: % vs. .format — 只处理方法 1 和 2,并询问哪个更好;我的问题是关于 Python 禅宗的明确弃用
String formatting options: pros and cons — 在问题中只处理方法 1a 和 1b,在答案中处理 1 和 2,也没有关于弃用的内容
advanced string formatting vs template strings — 主要是关于方法 1 和 3,不涉及弃用
String formatting expressions (Python) — 答案提到 计划弃用原始的 '%' 方法。但是计划弃用、待弃用和实际弃用有什么区别呢?而且
printf
风格的方法甚至不会引发PendingDeprecationWarning
,所以这真的会被弃用吗?这个帖子也比较老了,信息可能已经过时了。
另见
最佳答案
新的.format()
method旨在替换旧的 %
格式语法。后者已被淡化,(但尚未正式弃用)。方法文档说明了很多:
This method of string formatting is the new standard in Python 3, and should be preferred to the
%
formatting described in String Formatting Operations in new code.
(强调我的)。
为了保持向后兼容性并使转换更容易,旧格式已保留现在。来自原文PEP 3101 proposal :
Backwards Compatibility
Backwards compatibility can be maintained by leaving the existing mechanisms in place. The new system does not collide with any of the method names of the existing string formatting techniques, so both systems can co-exist until it comes time to deprecate the older system.
注意直到弃用旧系统;它还没有被弃用,但新系统将在您编写新代码时使用。
新系统的一个优点是您可以结合旧的 %
格式化程序的元组和字典方法:
"{greeting}, {0}".format(world, greeting='Hello')
并且可以通过 object.__format__()
钩子(Hook)进行扩展,该钩子(Hook)用于处理单个值的格式化。
请注意,旧系统有 %
和 Template
类,后者允许您创建添加或更改其行为的子类。新式系统有Formatter
class填补同样的空白。
Python 3 已进一步远离弃用,而是在 printf
-style String Formatting section 中向您发出警告:
Note: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals or the
str.format()
interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.
Python 3.6 还添加了 formatted string literals , 将表达式 嵌入 格式字符串。这些是使用内插值创建字符串的最快方法,并且应该在可以使用文字的任何地方代替 str.format()
使用。
关于Python 的多种字符串格式化方式——旧的(将要被)弃用了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13451989/