>> name = "George" >>> pr-6ren">
gpt4 book ai didi

python - python-3.6 中带有 'f' 前缀的字符串

转载 作者:IT老高 更新时间:2023-10-28 20:31:05 25 4
gpt4 key购买 nike

我正在试用 Python 3.6。在浏览新代码时,我偶然发现了这种新语法:

f"My formatting string!"

看来我们可以这样做:

>>> name = "George"
>>> print(f"My cool string is called {name}.")
My cool string is called George.

任何人都可以阐明其内部工作原理吗?特别是 f 前缀字符串可以采用的变量范围是什么?

最佳答案

PEP 498 Literal String Interpolation :

The expressions that are extracted from the string are evaluated in the context where the f-string appeared. This means the expression has full access to local and global variables. Any valid Python expression can be used, including function and method calls.

因此,表达式被评估为好像它们出现在相同的范围内;局部变量、闭包和全局变量的工作方式与同一上下文中的其他代码相同。

您可以在 reference documentation 中找到更多详细信息:

Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and a lambda expression must be surrounded by explicit parentheses. Replacement expressions can contain line breaks (e.g. in triple-quoted strings), but they cannot contain comments. Each expression is evaluated in the context where the formatted string literal appears, in order from left to right.

由于您正在尝试 3.6 alpha 版本,请务必阅读 What's New In Python 3.6 documentation .它总结了所有更改,包括相关文档和 PEP 的链接。

需要明确一点:3.6 尚未发布;第一个 alpha 版预计要到 2016 年 5 月才会发布。请参阅 3.6 release schedule .

关于python - python-3.6 中带有 'f' 前缀的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35745050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com