为什么我不能在 f 字符串中调用 dict.get()? (Python 3.8.1)

Why can't I call dict.get() in f-string? (Python 3.8.1)

问题

当我从 Python >3.8 中的 f 字符串中调用 .get() 时,是否有人对初学者有友好的解释?

问题

当我直接在 f 字符串中调用 dict.get() 时,我得到了 SyntaxError。 如果我将 dict.get() 调用存储在一个变量中并在 f 字符串中引用该变量,它可以正常工作。

这有效

def new_item():
    desc = request.form.get('description', 'No description found')
    return f'Your new item to insert\nDescription:{desc}'

http://127.0.0.1:5000/new_item 显示:

这行不通

def new_item():
    return f'Your new item to insert\nDescription:{request.form.get('description', 'No description found')}'

SyntaxError: invalid syntax

File ".\server.py", line 39
    return f'Your new item to insert\nDescription:{request.form.get('description', 'No description found')}'
                                                             ^

我的研究

Whosebug 充满了问题 (, , here, here) and/or 问题,只需调用适当的 Python 版本即可解决。 我确实安装了这样一个 Python 版本,并且也在调用适当的命令(事实上,f-string 在上面的示例中有效)。无论如何,这是 powershell:

> python
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32

经过一些额外的研究(参见 here),我的问题的解决方案如下:

我用单引号字符串调用字典 属性。 f 字符串文字将单引号解释为字符串的结尾,随后抛出 SyntaxError。

解决方案

1) 不要用单引号调用字典 属性,而是用双引号调用它,如下所示:

def new_item():
    return f'Your new item to insert\nDescription:{request.form.get("description", "No description found")}'

正如@Todd 在评论中指出的那样,还有更多解决方案。为了完整起见:

2) Invert 1) -- 对 f 字符串使用双引号,对其中的任何字符串使用单引号。

3) 使用反斜杠 \ 转义引号 char

4) 在字符串上使用三重双引号,然后在其中使用任何内容

5) 单独存储字典值(就像在问题的工作解决方案中一样)。正如@chepner 指出的那样,这具有尊重 max line length limit 和提高可读性的优点。

--

感谢大家通过评论做出贡献。我已投票。