[issue5237] Allow auto-numbered replacement fields in str.format() strings
Eric Smith
report at bugs.python.org
Sat Mar 14 02:35:43 CET 2009
Eric Smith <eric at trueblade.com> added the comment:
I believe this patch is complete. I need to add tests and documentation,
but the code itself should be finished.
Here's the normal case:
>>> '{} {}'.format('test', 0)
'test 0'
It also handles error checking:
>>> '{1} {}'.format('test', 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot switch from manual field specification to automatic
field numbering
>>> '{} {1}'.format('test', 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot switch from automatic field numbering to manual field
specification
You can use named fields along with auto-numbered fields:
>>> '{test} {}'.format(1, test=2)
'2 1'
You can nest either named or auto-numbered fields:
>>> '{:^{}}'.format('x', 10)
' x '
>>> 'pi={:{fmt}} {:{fmt}}'.format(3.1415, 2.71828, fmt='1.4f')
'pi=3.1415 2.7183'
Attribute access is supported:
>>> '{.__abs__}'.format(0)
"<method-wrapper '__abs__' of int object at 0x85db8f8>"
As is subscripting:
>>> '{[x]}'.format({'x':4})
'4'
>>> '{[1]}'.format([1, 2])
'2'
I'll work on the tests over the weekend, then commit to trunk and py3k.
We need to decide what to do about string.Formatter (which I just
realized I erroneously called string.Format in the previous message).
----------
Added file: http://bugs.python.org/file13326/issue5237-0.patch
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue5237>
_______________________________________
More information about the Python-bugs-list
mailing list