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 class
中,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
,那么这真的会被弃用吗?此帖子也相当古老,因此信息可能已过时。
Formatter
类吗? - Martijn Pieters