Python has at least six ways of formatting a string:
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'
A brief history of the different methods:
printf
-style formatting has been around since Pythons infancyTemplate
class was introduced in Python 2.4format
method was introduced in Python 2.6 f
-strings were introduced in Python 3.6My questions are:
printf
-style formatting deprecated or going to be deprecated?Template class
, is the substitute
method deprecated or going to be deprecated? (I'm not talking about safe_substitute
, which as I understand it offers unique capabilities)Similar questions and why I think they're not duplicates:
Python string formatting: % vs. .format — treats only methods 1 and 2, and asks which one is better; my question is explicitly about deprecation in the light of the Zen of Python
String formatting options: pros and cons — treats only methods 1a and 1b in the question, 1 and 2 in the answer, and also nothing about deprecation
advanced string formatting vs template strings — mostly about methods 1 and 3, and doesn't address deprecation
String formatting expressions (Python) — answer mentions that the original '%' approach is planned to be deprecated. But what's the difference between planned to be deprecated, pending deprecation and actual deprecation? And the printf
-style method doesn't raise even a PendingDeprecationWarning
, so is this really going to be deprecated? This post is also quite old, so the information may be outdated.