Graic
Graic

Reputation: 59

Slicing a string from inside a formatted string gives 'TypeError: string indices must be integers'

Shouldn't both these commands do the same thing?

>>> "{0[0:5]}".format("lorem ipsum")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> "{0}".format("lorem ipsum"[0:5])
'lorem'

The commands

>>> "{0[0]}".format("lorem ipsum")
'l'

and

>>> "{0}".format("lorem ipsum"[0])
'l'

evaluate the same. (I know that I can use other methods to do this, I am mainly just curious as to why it dosen't work)

Upvotes: 3

Views: 71

Answers (1)

Davis Herring
Davis Herring

Reputation: 40063

The str.format syntax is handled by the library and supports only a few “expression” syntaxes that are not the same as regular Python syntax. For example,

"{0[foo]}".format(dict(foo=2))  # "2"

works without quotes around the dictionary key. Of course, there are limitations from this simplicity, like not being able to refer to a key with a ] in it, or interpreting a slice, as in your example.

Note that the f-strings mentioned by kendall are handled by the compiler and (fittingly) use (almost) unrestricted expression syntax. They need that power since they lack the obvious alternative of placing those expressions in the argument list to format.

Upvotes: 1

Related Questions