[New-bugs-announce] [issue33669] str.format should raise exception when placeholder number doesn't match argument number

Xiang Zhang report at bugs.python.org
Mon May 28 10:57:29 EDT 2018


New submission from Xiang Zhang <angwerzx at 126.com>:

I'm somewhat surprised when I have code like `"hello %s".format(person)` in my project there is no exception raised and "hello %s" returned. Have several tries it seems `str.format` won't check argument number.

>>> '{} {}'.format(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> '{} {}'.format(1, 2, 3)
'1 2'
>>> ''.format(1, 2, 3)
''
>>>

The IndexError is not ideal. I think this behavior could be improved since it's highly possible such code is an oversight bug. The old format string does a good job in this place:

>>> "%s %s" % 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> "%s %s" % (1,2,3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>> "" % 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

----------
components: Interpreter Core
messages: 317859
nosy: xiang.zhang
priority: normal
severity: normal
status: open
title: str.format should raise exception when placeholder number doesn't match argument number
type: behavior
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue33669>
_______________________________________


More information about the New-bugs-announce mailing list