-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
string.Formatter accepts empty fields but displays wrong when nested #69222
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Since 3.4.1, string.Formatter() accepts empty keys {}. If these are nested they give different results from explicitly numbered, where the same arguments applied "".format() give the expected results: from string import Formatter
f = Formatter()
fmt0 = "X {:<{}} {} X"
fmt1 = "X {0:<{1}} {2} X"
for fmt in [fmt0, fmt1]:
x = f.format(fmt, 'ab', 5, 1)
y = fmt.format( 'ab', 5, 1)
print(x)
print(y)
gives:
of which the first line is incorrect. |
Here is a patch for Python-3.5.0rc3/Lib/test/test_string.py unittests fail: --- /opt/python/3.5/lib/python3.5/test/test_string.py 2015-09-08 17:06:07.099197904 +0200
+++ test_string.py 2015-09-08 21:47:01.471634309 +0200
@@ -58,6 +58,8 @@
'foo{1}{num}{1}'.format(None, 'bar', num=6))
self.assertEqual(fmt.format('{:^{}}', 'bar', 6),
'{:^{}}'.format('bar', 6))
+ self.assertEqual(fmt.format('{:^{}} {}', 'bar', 6, 'X'),
+ '{:^{}} {}'.format('bar', 6, 'X'))
self.assertEqual(fmt.format('{:^{pad}}{}', 'foo', 'bar', pad=6),
'{:^{pad}}{}'.format('foo', 'bar', pad=6)) |
The problem lies in the recursive call to _vformat which might consume fields without name ({}) and increment auto_arg_index, but that Since the line became longer than PEP-8 allowed I wrapped all of the method call arguments to the next line, hope that that's ok. The patch is against the mercurial repository and works for 3.4.1 upwards. |
New changeset 9eae18e8af66 by Eric V. Smith in branch '3.4': New changeset 65d7b4fd0332 by Eric V. Smith in branch '3.5': New changeset aef6365294c8 by Eric V. Smith in branch 'default': |
Fixed in 3.4, 3.5, and 3.6. Thanks for the bug report and patch! I added you to the Misc/ACKS file. |
I don't suppose this change could make it into 2.7.11 as well? Thanks, |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: