Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an "invalid syntax" when trying to perform string interpolation

I have recently been learning python 3 and I cannot get any examples involving string interpolation (formatting) to work.

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. 

I am on Ubuntu 16.04:

python3 --version Python 3.5.2 

Am I just overlooking basic syntax? I have run the same commands on a few computers from fellow students and it seems to execute just fine.

like image 938
Sven E Avatar asked Feb 09 '17 01:02

Sven E


People also ask

What does invalid syntax string mean?

It tells you that you can't assign a value to a function call. The second and third examples try to assign a string and an integer to literals. The same rule is true for other literal values. Once again, the traceback messages indicate that the problem occurs when you attempt to assign a value to a literal.

Why does Python say invalid syntax?

Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.

What is F in print in Python?

What is print(f”…”) Print(f Python): The f means Formatted string literals and it's new in Python 3.6 . The f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast.


2 Answers

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.

like image 161
yeputons Avatar answered Oct 24 '22 08:10

yeputons


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.

like image 44
Ritesh Kankonkar Avatar answered Oct 24 '22 09:10

Ritesh Kankonkar