Python Forum

Full Version: Strange syntax error with f-strings
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello Python experts,

can someone please explain me why this code produces a syntax error:
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}

print(f'Sarah\'s favorite language is {favorite_languages['sarah']}.')


On the other hand, the following code works fine:
print(f'Sarah\'s favorite language is {favorite_languages["sarah"]}.')


Another solution is:
print(f"Sarah\'s favorite language is {favorite_languages['sarah']}.")

Interesting, when using double quotes ["sarah"] code snippet works as intended.
I'm using Python 3.8.5.

I know that the problem is caused by "closing the string" but escape (\) doesn't solve it.
I don't like mixing " and ' when working with strings, but this time I need to make an exception or to use an auxiliary variable.
In fact you found the solution yourself.
(Oct-16-2020, 08:55 AM)Askic Wrote: [ -> ]print(f'Sarah\'s favorite language is {favorite_languages['sarah']}.')

The reason: the quoted string ends with the first (un-escaped) quote. So this is the string Python sees:
'Sarah\'s favorite language is {favorite_languages['
And then Python would ask: what do you mean with the rest. Your solution is correct: you must use different quotes within the string.
Because in the one with the error, the f-string is enclosed in single quotes and you also enclose the key inside the string. As you have discovered you need to enclose the string or the key with double quotes.

so it parse it as f-string f'Sarah\'s favorite language is {favorite_languages[' then variable sarah and then string ']}.' And it's syntax error because there is no comma between them
in the first one, you have quotes within quotes, so use this format
print(f"Sarah's favorite language is {favorite_languages['sarah']}.")
Thank you guys, I know what is the cause of the syntax error. I tried to use escape character '\' just like I would used in f'Sarah\'s... but it didn't work inside the bracket.

Since I prefer to use only single quote (') when working with strings, I solved the problem by using another auxiliary variable.
You could always use the format method if you dont like mixes strings. I do on occasion when i have numerous variables and i want to see the layout in the string better when the variables within are cluttering it up.
print('Sarah\'s favorite language is {}.'.format(favorite_languages['sarah']))
Thank you metulburr!