我最近一直在学习python 3,我无法得到任何涉及字符串插值(格式化)的例子。
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
我认为我的机器默认为python 2,但快速检查显示:
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.
我在Ubuntu 16.04:
python3 --version
Python 3.5.2
我只是忽略了基本语法?我在同学的几台计算机上运行相同的命令,似乎执行得很好。
正如Josh Lee在评论部分所建议的那样,仅在Python 3.6中添加了这种字符串插值,请参阅What’s New In Python 3.6(这里称为“PEP 498:Formatted string literals”)。
但是,您似乎使用的是Python 3.5.2,它不支持该语法。