Python 3 returns “invalid syntax” when trying to perform string interpolation

試著忘記壹切 提交于 2019-11-26 05:58:49

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42126794/python-3-returns-invalid-syntax-when-trying-to-perform-string-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!