Extracted as a side-topic from Deprecate str % format operator
While %-style formatting has become much less used in favor of {}-style formatting, particularly boosted through f-strings, there are still reasonable use cases where % placeholders are better suited compared to {} placeholders (e.g. formatting TeX, dynamically creating jinja templates or regexes, where curly braces are often used literally and would need to be escaped).
The %
formatting operator has some quirks in interpreting it’s operand: If only a single value is used, the variables can be used directly "%s" % var
unless it’s a tuple in which case the the tuple would be unpacked and only formatting would apply to the elements inside.
I propose to add a new str
method working on %-placeholders. Naming could be either .pformat()
(“percent format”) to rhyme with .format()
or .sprintf()
to rhyme with other languages. Like .format()
the method would support positional or keyword arguments. These would be equivalent:
"spam and {}".format("ham")
"spam and %s".pformat("ham")
"spam and {food}".format(food="ham")
"spam and %(food)s".pformat(food="ham")
Why is this reasonable:
- One can still use %-placeholders
- One does not have to work around the quirks of the %-formatting operator
- Strong analogy to the
.format()
function, which makes it easier to learn/read. - The % formatting operator can be hard to read (is
pattern % count
a math operation or a string formatting operation) - The % formatting operator may be less known among newer Python users as they will primarily learn f-strings. A
.pformat()
or.sprintf()
method is easier to look up for them. - Implementation is simple - the method is only a handful lines lines of code when when building it on top of the operator.
Possible counter arguments:
- Its use is rare enough that we shouldn’t bother with it. - Yes it’s a tradeoff, but it has its benefits and the needed effort is limited.