Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

f-string affected by quotation [duplicate]

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.

like image 462
ale123 Avatar asked Dec 02 '25 17:12

ale123


1 Answers

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:

>>> songs = ['Take me back to Eden', 'Alkaline', 'Ascensionism']
>>> f"This is the playlist: {", ".join(songs)}"
'This is the playlist: Take me back to Eden, Alkaline, Ascensionism'
like image 56
GreenButterfly Avatar answered Dec 05 '25 08:12

GreenButterfly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!