3

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)

1
  • 1
    Questions about why particular features aren't implemented in Python are not really in the scope of a good Stack Overflow question. "Because that's how it's designed to work" is not necessarily a satisfying answer. All we have are opinions, unless one of the Python developers happens by. However, I will note that f-strings do support slicing. Commented Apr 24, 2019 at 23:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.