list indices must be integers or slices, not str

Chris Angelico rosuav at gmail.com
Wed Jul 20 07:14:20 EDT 2022


On Wed, 20 Jul 2022 at 21:06, Frank Millman <frank at chagford.com> wrote:
> I saw this from Paul Rubin - for some reason his posts appear in google
> groups, but not python-list.
>
> "It seems to only want integer constants. x[2+2] and x[k] where k=2
> don't work either.

Yes, that's for the same reason that x[spam] can be used usefully with
a dictionary. Otherwise you'd need to use quotes. It makes perfect
sense that both 2+2 and k are treated as strings.

> I think the preferred style these days is f'{x[-1]}' which works."

Not true; there's no single "preferred style", and f-strings are
absolutely NOT replacements for everything else. They have their
place, as do the others. Yes, including percent formatting, it is not
deprecated, and it's really tiresome when people claim that it is.

> Unfortunately the 'f' option does not work for me in this case, as I am
> using a string object, not a string literal.

Right. An f-string uses the exact syntax of a Python expression, which
is often too powerful, but also restricts it to the string literal
style (since it's actual code, not a method call). For other purposes,
.format() is a better choice.

ChrisA


More information about the Python-list mailing list