尝试执行字符串插值时,Python 3 返回“无效语法”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42126794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3 returns "invalid syntax" when trying to perform string interpolation
提问by Sven E
I have recently been learning python 3 and I cannot get any examples involving string interpolation (formatting) to work.
我最近一直在学习 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
I figured my machine was defaulting to python 2, but a quick check reveals:
我认为我的机器默认为 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.
I am on Ubuntu 16.04:
我在 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.
我只是忽略了基本语法吗?我已经在同学的几台计算机上运行了相同的命令,它似乎执行得很好。
回答by yeputons
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").
正如 Josh Lee 在评论部分所建议的那样,这种字符串插值仅在 Python 3.6 中添加,请参阅Python 3.6 中的新增功能(此处称为“ PEP 498:格式化字符串文字”)。
You, however, seems to be using Python 3.5.2, which does not support that syntax.
但是,您似乎使用的是不支持该语法的 Python 3.5.2。
回答by Ritesh Kankonkar
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.
.format 适用于 3.5。在这里为可能需要它以解决类似问题的人记录它。