Search code examples
pythontuplesf-string

Why does indexing anonymous tuple in f-string give an error?


I am trying to understand why this is happening:

>>> selection = False
>>> a = ("NO", "YES")
>>> print(f"{a[int(selection)]}")
NO
>>> print(f"{("NO", "YES")[int(selection)]}")
  File "<stdin>", line 1
    print(f"{("NO", "YES")[int(selection)]}")
                ^
SyntaxError: invalid syntax

All I think I know about Python makes me think that this should work just fine, but since it obviously is not, there is a learning opportunity here.

Can someone explain why is indexing anonymous tuple not recognized as valid syntax in Python (3.7.3), please?

NOTE: I am not looking for alternate ways to do this, but to learn and understand this particular error, if possible.


Solution

  • The quotation marks are the problem. They terminate the f-string and need to be escaped or replaced by '.