pythonpython-3.6f-string

f-string affected by quotation


alien_o = {"Colour" : "Green"}
print(f"The colour is now {alien_o["Colour"]}.")

What's wrong with these lines of code? The closing bracket and the curly bracket is affected by the quotes, and I don't understand why.


Solution

  • It mixes up the ", try using 'Colour' instead of "Colour".

    Because it thinks that the format string is f"The colour is now {alien_o[", which is not what you want.

    Python 3.12 and later

    As of Python 3.12, what OP posted is now valid syntax. Specifically, this is new:

    Quote reuse: in Python 3.11, reusing the same quotes as the enclosing f-string raises a SyntaxError, forcing the user to either use other available quotes (like using double quotes or triple quotes if the f-string uses single quotes). In Python 3.12, you can now do things like this