为什么我从 f 字符串中得到“无效语法”? [重复]

问题描述 投票:0回答:3

我无法让 f 字符串在 Python 3 中工作。我在 REPL 上尝试过:

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.

出了什么问题,如何解决?

python python-3.x syntax-error python-3.5
3个回答
96
投票

正如 Josh Lee 在评论部分中所建议的,这种字符串插值仅在 Python 3.6 中添加,请参阅Python 3.6 中的新增功能(这里称为“PEP 498:格式化字符串文字”)。

但是,您似乎使用的是Python 3.5.2,它不支持该语法。


21
投票

这是一个非常老的问题,不确定是否在其他地方得到了回答,但遇到了同样的问题并出现在一些令人困惑的页面上。几分钟后就明白了。下面的线应该可以工作。

my_message = "I live in {}".format(state)

.format 适用于 3.5。在这里为可能需要它来解决类似问题的人记录下来。


-13
投票

对我有用的(在 sublime 中的 python 3.8.5 中)是删除 f。

message = "I live in {state}"

我发现比

.format(state)

更容易
© www.soinside.com 2019 - 2024. All rights reserved.