New submission from Germán L. Osella Massa <gose...@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 <rep...@bugs.python.org>
<http://bugs.python.org/issue8985>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to