문제

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,…)?

도움이 되었습니까?

해결책

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 "{}".

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top