pythonsyntax-errorf-string

f-strings giving SyntaxError?


I tried this code, following along with a tutorial:

my_name = 'Zed A. Shaw'

print(f"Let's talk about {my_name}.")

But I get an error message highlighting the last line, like so:

    print(f"Let's talk about {my_name}.")
                                       ^
SyntaxError: invalid syntax

Why?


If you get an error like this from someone else's code, do not try to fix it yourself - the other project simply does not support your Python version (One example: Using pytesseract on Python 2.7 and Windows XP). Look for an alternative instead, or check the project's documentation or other support resources for a workaround.

In particular, the built-in pip package manager has an issue where newer versions of pip require a newer Python version, so old installations cannot upgrade pip past a certain point. See Installing pip is not working in python < 3.6 or Upgrading pip fails with syntax error caused by sys.stderr.write(f"ERROR: {exc}") for details.

If an external tool warns about the problem even though Python supports the feature, update the tool. See Getting invalid syntax error when using Pylint but code runs fine for an example.

This question is specifically about the situation where any attempt to use f-strings fails (the ^ in the error message will point at the closing quote). For common problems with specific f-string syntax, see How do I escape curly-brace ({}) characters characters in a string while using .format?, f-string formula inside curly brackets not working, Discord.py - SyntaxError f-string: empty expression not allowed, How can I use newline '\n' in an f-string to format a list of strings?, How to fix Unterminated expression in f-string; missing close brace in python?.

For a general overview of the f-string feature, see String with 'f' prefix in python-3.6.

For details on alternate approaches to string formatting, see How do I put a variable’s value inside a string (interpolate it into the string)?.


Solution

  • I think you have an old version of python. try upgrading to the latest version of python. F-string literals have been added to python since python 3.6. you can check more about it here