This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Custom string formatter doesn't work like builtin str.format
Type: Stage:
Components: Versions: Python 3.2, Python 3.3, Python 2.7
process
Status: closed Resolution: duplicate
Dependencies: Superseder: string.Formatter doesn't support empty curly braces "{}"
View: 13598
Assigned To: Nosy List: PaulMcMillan, eric.smith, terry.reedy
Priority: normal Keywords:

Created on 2012-03-14 02:02 by PaulMcMillan, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg155708 - (view) Author: Paul McMillan (PaulMcMillan) * Date: 2012-03-14 02:02
In Python 2.7, I can use an empty format string to indicate automatically numbered positional arguments when formatting the builtin string object.

http://docs.python.org/release/2.7/library/string.html#format-string-syntax

If I subclass string.Formatter, this expected functionality doesn't work.
http://docs.python.org/release/2.7/library/string.html#string-formatting


Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from string import Formatter
>>> class MyFormatter(Formatter):
...     pass
... 
>>> fs_a = 'a{0}b{1}c'
>>> fs_b = 'a{}b{}c'
>>> fs_a.format(1, 2)
'a1b2c'
>>> fs_b.format(1, 2)
'a1b2c'
>>> fmt = MyFormatter()
>>> fmt.format(fs_a, 1, 2)
'a1b2c'
>>> fmt.format(fs_b, 1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/string.py", line 545, in format
    return self.vformat(format_string, args, kwargs)
  File "/usr/lib/python2.7/string.py", line 549, in vformat
    result = self._vformat(format_string, args, kwargs, used_args, 2)
  File "/usr/lib/python2.7/string.py", line 571, in _vformat
    obj, arg_used = self.get_field(field_name, args, kwargs)
  File "/usr/lib/python2.7/string.py", line 632, in get_field
    obj = self.get_value(first, args, kwargs)
  File "/usr/lib/python2.7/string.py", line 591, in get_value
    return kwargs[key]
KeyError: ''
msg156070 - (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2012-03-16 19:21
We know that string.Formatter does not properly duplicate str.format.
#13598 is specifically about use of {}.
Search "string Formatter" for other related issues.
History
Date User Action Args
2022-04-11 14:57:27adminsetgithub: 58505
2012-03-16 19:21:15terry.reedysetstatus: open -> closed

nosy: + terry.reedy
messages: + msg156070

superseder: string.Formatter doesn't support empty curly braces "{}"
resolution: duplicate
2012-03-14 02:18:01r.david.murraysetnosy: + eric.smith

versions: + Python 3.2, Python 3.3
2012-03-14 02:02:59PaulMcMillancreate