77

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sven E
  • 848
  • 1
  • 6
  • 8
  • 3
    What version of python were the others using? You seem to have answered your own question. https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals – Josh Lee Feb 09 '17 at 01:42
  • @yeputons, avoid answering questions in the comments. Add an answer. – Adrian Sanguineti Feb 09 '17 at 02:24
  • It's a close call, but I think the answers for the other question were slightly better overall, so I'm making that one the canonical. – Karl Knechtel Jan 22 '23 at 02:59

3 Answers3

95

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").

You, however, seems to be using Python 3.5.2, which does not support that syntax.

yeputons
  • 8,478
  • 34
  • 67
21

This is a pretty old question and not sure if answered somewhere else, but ran into same problem and landed on some confusing pages. Figured out a couple of minutes later. Below line should work.

my_message = "I live in {}".format(state)

.format works for 3.5. Documenting it here for someone who may need it for similar issue.

Ritesh Kankonkar
  • 363
  • 3
  • 12
-13

What worked for me (in python 3.8.5 in sublime) was removing the f.

message = "I live in {state}"

I find it easier than .format(state)

  • 11
    Well, it "works" in the sense that it doesn't give a syntax error... whether it does what was intended is another question. – fool4jesus Sep 08 '20 at 12:54
  • This will not throw an error but it will not interpolate your `state` value in the string output. – Sven E Apr 20 '22 at 17:21