Python 的多种字符串格式化方式——旧的(将要被)弃用了吗?

标签 python printf string-formatting deprecated backwards-compatibility

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,据我了解,它提供了独特的功能)

类似的问题以及为什么我认为它们不是重复的:

另见

最佳答案

新的.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/

相关文章:

python - Scrapy,使用不同的 XPathSelector 进行递归爬行

python - 从不同的工作目录导入 Python 模块

python - Django/Python 应用程序和开发环境的先决条件

java - 如何将一位数整数变成两位数

c++ - 如何使用参数集合格式化 std::string?

python - 进行字符串格式化时,字段名称中出现意外的 '{'

c# - 如何将数字格式化为没有百分号的百分比?

python - sqlalchemy:空比较交换性

Ruby zerofill 一个字符串

bash - 如何将 printf 语句的结果分配给变量(前导零)?