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

标签 python scope string-formatting python-3.6 f-string

我正在试用 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/

相关文章:

Python - 多处理错误 'cannot start a process twice'

python - socket.error : [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

python - pandas 通过非 nan 值之前和之后填充 nans

ruby-on-rails - (Ruby,Rails)模块和库中 SELF 的上下文......?

java - 根据规则解析字符串内容的库

python - 获取 python stdlib 版本,而不是解释器版本

c - for 循环中的变量作用域

javascript - Angular 代码未显示在 html 页面上

c# - String.Format 从 "2.4k"得到 "2400"

java - Java 的 JSON 美化器库