Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.Formatter does not accept "{}" template?

Python's Formatter class "allows you to create and customize your own string formatting behaviors using the same implementation as the built-in format() method". Since one can do

>>> '{}'.format(3.14)
'3.14'

and

>>> format(3.14, '')
'3.14'

I was expecting the following to work too:

>>> string.Formatter().format('{}', 3.14)
(…)
KeyError: ''

Is there any standard way of handling this very usual and simple formatting string with a Formatter? or must the Formatter be customized before behaving more like Python's format()? is this really doable in a robust way (thread-safe,…)?

like image 607
Eric O Lebigot Avatar asked Apr 25 '26 11:04

Eric O Lebigot


1 Answers

The original implementation of new-style string formatting in Python 2.6/3.0 did not allow empty {} templates. The change that allows them is documented as issue 5237: Allow auto-numbered replacement fields in str.format() strings. On that page, message 83559 from Eric V. Smith ponders the question whether string.Format also should support auto-numbering (I suppose he means string.Formatter) and concludes against it.

A patch has been proposed in issue 13598: string.Formatter doesn't support empty curly braces "{}".

like image 72
Janne Karila Avatar answered Apr 26 '26 23:04

Janne Karila