Search code examples
pythonpython-3.xsyntax-errorpython-3.5

Why am I getting "invalid syntax" from an f-string?


I cannot get f-strings to work in Python 3. I tried this at the REPL:

In [1]: state = "Washington"

In [2]: state
Out[2]: 'Washington'

In [3]: my_message = f"I live in {state}"
File "<ipython-input-3-d004dd9e0255>", line 1
my_message = f"I live in {state}"
                                ^
SyntaxError: invalid syntax

I figured my machine was defaulting to python 2, but a quick check reveals:

Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
Type "copyright", "credits" or "license" for more information.

IPython 5.2.2 -- An enhanced Interactive Python.

What is wrong, and how do I fix it?


Solution

  • As suggested by Josh Lee in the comment section, that kind of string interpolation was added in Python 3.6 only, see What’s New In Python 3.6 (here it's called "PEP 498: Formatted string literals").

    However, you seem to be using Python 3.5.2, which does not support that syntax.