获取“无效语法"尝试执行字符串插值时 [英] Getting an "invalid syntax" when trying to perform string interpolation
问题描述
我最近一直在学习 python 3,但我无法得到任何涉及字符串插值(格式化)的示例.
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
我认为我的机器默认使用 python 2,但快速检查显示:
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.
我使用的是 Ubuntu 16.04:
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.
推荐答案
正如 Josh Lee 在评论部分所建议的那样,这种字符串插值仅在 Python 3.6 中添加,请参阅 Python 3.6 的新功能(这里称为PEP 498:格式化字符串文字").
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").
然而,您似乎使用的是不支持该语法的 Python 3.5.2.
You, however, seems to be using Python 3.5.2, which does not support that syntax.
这篇关于获取“无效语法"尝试执行字符串插值时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!