Search code examples
pythonpython-3.xf-string

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


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.


Solution

  • 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.