Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested quotes in f-string with Python 3.12 vs older versions [duplicate]

With Python 3.12 I can do the following without error:

a = "abc"
s = f"{a.replace("b", "x")}"

Note the nested " characters.

With Python 3.6 the same will throw a SyntaxError because closing ) and } are missing in this part f"{a.replace(".

Why is that? I would have expected a SyntaxError with 3.12 as well.

like image 796
pktl2k Avatar asked Dec 06 '25 07:12

pktl2k


1 Answers

Python 3.12 implements PEP 701, that allows the usage of the same quote character as the outer f-string itself

>>> 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'

So if you are running 3.12 on one system and an older version on the other, the difference is to be expected.

like image 76
Tzane Avatar answered Dec 08 '25 20:12

Tzane



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!