Search code examples
pythonf-string

Why do not f-strings work in comprehensions inside other f-strings?


I would like to use an f-string inside a generator which I put inside another f-string, such as here:

MORSE_CODE = {'123' : '456', '789' : 'qwe'}
print(f'{(f'{key}, {value}' for key, value in MORSE_CODE.items())}')

When this was run I got the next error:

  File "<ipython-input-10-05579b450d5e>", line 2
    print(f'{(f'{key}, {value}' for key, value in MORSE_CODE.items())}')
                ^
SyntaxError: invalid syntax

At first I thought that it is impossible to use f-strings within generators but, when I put it (f'{key}, {value}' for key, value in MORSE_CODE.items()) into variable, this worked:

a = (f'{key}, {value}' for key, value in MORSE_CODE.items())
print(f'{{{a}}}')

{<generator object <genexpr> at 0x0000025EE94EF200>}

How does this work in Python? I could not google this information about working f-strings into generators inside another f-strings. What is the difference between these pieces of code?


Solution

  • Not sure what the expected output is, but when making use of the different string quotes " and ' the parser can differentiate between the start of the inner f-string and the end of the outer.

    MORSE_CODE = {'123' : '456', '789' : 'qwe'}
    print(f'{(f"{key}, {value}" for key, value in MORSE_CODE.items())}')