list indices must be integers or slices, not str

Peter Otten __peter__ at web.de
Wed Jul 20 09:42:27 EDT 2022


On 20/07/2022 11:37, Chris Angelico wrote:
> On Wed, 20 Jul 2022 at 18:34, Frank Millman <frank at chagford.com> wrote:
>>
>> Hi all
>>
>> C:\Users\E7280>python
>> Python 3.9.7 (tags/v3.9.7:1016ef3, Aug 30 2021, 20:19:38) [MSC v.1929 64
>> bit (AMD64)] on win32
>> Type "help", "copyright", "credits" or "license" for more information.
>>   >>>
>>   >>> x = list(range(10))
>>   >>>
>>   >>> '{x[1]}'.format(**vars())
>> '1'
>>   >>>
>>   >>> '{x[-1]}'.format(**vars())
>> Traceback (most recent call last):
>>     File "<stdin>", line 1, in <module>
>> TypeError: list indices must be integers or slices, not str
>>   >>>
>>
>> Can anyone explain this error? It seems that a negative index is deemed
>> to be a string in this case.
>>
>
> Yeah, that does seem a little odd. What you're seeing is the same as
> this phenomenon:
>
>>>> "{x[1]} {x[spam]}".format(x={1: 42, "spam": "ham"})
> '42 ham'
>>>> "{x[1]} {x[spam]}".format(x={"1": 42, "spam": "ham"})
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> KeyError: 1
>
> But I can't find it documented anywhere that digits-only means
> numeric.


I found

https://peps.python.org/pep-3101/

"""
PEP 3101 – Advanced String Formatting
...
An example of the ‘getitem’ syntax:

"My name is {0[name]}".format(dict(name='Fred'))

It should be noted that the use of ‘getitem’ within a format string is
much more limited than its conventional usage. In the above example, the
string ‘name’ really is the literal string ‘name’, not a variable named
‘name’. The rules for parsing an item key are very simple. If it starts
with a digit, then it is treated as a number, otherwise it is used as a
string.

Because keys are not quote-delimited, it is not possible to specify
arbitrary dictionary keys (e.g., the strings “10” or “:-]”) from within
a format string.
"""


More information about the Python-list mailing list