list indices must be integers or slices, not str
Roel Schroeven
roel at roelschroeven.net
Wed Jul 20 16:59:21 EDT 2022
Frank Millman schreef op 20/07/2022 om 13:04:
> >> On Wed, 20 Jul 2022 at 18:34, Frank Millman <frank at chagford.com> wrote:
> >>> >>>
> >>> >>> 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.
> >>>
> >>
> >> [...]
> >>
>
> "It seems to only want integer constants. x[2+2] and x[k] where k=2
> don't work either.
>
> I think the preferred style these days is f'{x[-1]}' which works."
>
> Unfortunately the 'f' option does not work for me in this case, as I am
> using a string object, not a string literal.
>
I've always found a bit dirty to pass indiscriminate symbol tables like
the one from globals() or vars() or vars(some_object) to a formatting
method, leaving the formatting string free to access any of it. I prefer
to make things more explicit. Can't you make a dict with a selection of
things you possible want to format?
In a sense I think you're looking for a more complete templating
solution than what Python's formatting mechanisms are designed for.
Maybe you should consider a full template engine, like Jinja?
--
"There is no cause so noble that it will not attract fuggheads."
-- Larry Niven
More information about the Python-list
mailing list