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 婴儿期以来一直存在
  • Python 2.4 中引入了 Template
  • Python 2.6 中引入了 format 方法
  • f -strings 是在 Python 3.6
  • 中引入的

    我的问题是:
  • printf 样式格式是否已弃用或将要弃用?
  • Template class 中, substitute 方法是被弃用还是将被弃用? (我不是在谈论 safe_substitute ,据我所知,它提供了独特的功能)

  • 类似的问题以及为什么我认为它们不是重复的:
  • Python string formatting: % vs. .format——只处理方法1和方法2,问哪个更好;根据 Python 的 Zen
  • ,我的问题是明确的弃用
  • String formatting options: pros and cons — 只处理问题中的方法 1a 和 1b,答案中的方法 1 和 2,也没有关于弃用的内容
  • advanced string formatting vs template strings — 主要是关于方法 1 和 3,并没有解决弃用问题
  • String formatting expressions (Python) — 答案提到计划弃用原始的 '%' 方法。但是计划弃用、待弃用和实际弃用之间有什么区别?并且 printf 风格的方法甚至不会引发 PendingDeprecationWarning ,所以这真的会被弃用吗?这个帖子也很老了,所以信息可能已经过时了。

  • 也可以看看
  • PEP 502: String Interpolation - Extended Discussion
  • String Formatter
  • 最佳答案

    虽然文档中有各种迹象表明 .format 和 f-strings 优于 % 字符串,但没有幸存的计划来弃用后者。

    在提交 Issue #14123: Explicitly mention that old style % string formatting has caveats but is not going away any time soon. 中,受问题 Indicate that there are no current plans to deprecate printf-style formatting 的启发,对 % 格式的文档进行了编辑以包含以下短语:



    (强调我的。)

    这个短语后来在提交 Close #4966: revamp the sequence docs in order to better explain the state of modern Python 中被删除。这似乎表明弃用 % 格式的计划又回来了……但是深入错误跟踪器显示其意图恰恰相反。在错误跟踪器上,提交的作者描述了更改 like this 的特征:



    换句话说,我们对 % 格式文档进行了两次连续更改,旨在明确强调它不会被弃用,更不用说删除了。这些文档仍然对不同类型的字符串格式的相对优点持保留意见,但他们也清楚 % 格式不会被弃用或删除。

    更重要的是,most recent change to that paragraph,在2017年3月,从这个改变了......



    ...到这个:



    请注意从“有助于避免”到“可能有助于避免”的变化,以及 .format 和 f-strings 的明确建议如何被关于每种风格如何“提供自己的权衡和好处”的蓬松、模棱两可的散文所取代。也就是说,不仅正式弃用不再出现,而且当前的文档公开承认 % 格式至少比其他方法有一些“好处”。

    我从这一切推断,弃用或删除 % 格式的运动不仅步履蹒跚,而且被彻底和永久地击败。

    关于Python 的多种字符串格式化方式——旧的(将要)被弃用了吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13451989/

    10-13 08:23