0

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.

Tammi
  • 421
  • 7
  • 12

1 Answers1

2

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

peer
  • 4,171
  • 8
  • 42
  • 73
  • 1
    [Escaping quotes doesn't work](https://www.python.org/dev/peps/pep-0498/#escape-sequences) in the expression portion of f-strings. Using single- instead of double-quotes is a more likely solution. – khelwood Apr 24 '20 at 11:04
  • Oh for ..... sake! *major facepalm*. Yes, indeed. You are absolutely right! – Tammi Apr 24 '20 at 11:04