[New-bugs-announce] [issue8985] String format() has problems parsing numeric indexes

Germán L. Osella Massa report at bugs.python.org
Sat Jun 12 22:14:01 CEST 2010


New submission from Germán L. Osella Massa <gosella at gmail.com>:

The str.format() method allows index lookup on an object that supports __getitem__(). However, negative indexes are not supported.

Examples (using Python 2.6.5):

>>> "{0[0]}".format([0, 1, 2])
'0'

>>> "{0[-1]}".format([0, 1, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

>>> u"{0[0]}".format([0, 1, 2])
u'0'
>>> u"{0[-1]}".format([0, 1, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not unicode

Also notice that spaces matter:

>>> "{0[ 0 ]}".format([0, 1, 2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str

(The same thing happens on Python 3.1.2)

The problem is that the function get_integer() on Objects/stringlib/string_format.h don't expect spaces or a '-' char, only digits. If the index is not a continuous sequence of digits, it assumes that it is a key for a dict and the index is treated as a string, and that's the cause of the TypeError exception.

This code is the same from 2.6.5 up to trunk.

get_integer() is not very robust to parsing numbers. I'm not familiar with CPython but perhaps the same code used in int(str) can be applied here to take advantage of the better parsing that int() has.

----------
components: Library (Lib), Unicode
messages: 107691
nosy: Germán.L..Osella.Massa
priority: normal
severity: normal
status: open
title: String format() has problems parsing numeric indexes
type: behavior
versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue8985>
_______________________________________


More information about the New-bugs-announce mailing list