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

String with 'f' prefix in python-3.6

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

所以表达式的计算就像它们出现在相同的范围内一样; locals、closures 和 globals 都与相同上下文中的其他代码一样工作。

您可以在 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.

f-strings 还支持花括号内的任何 Python 表达式。

print(f"My cool string is called {name.upper()}.")

可能还值得注意的是,这个 PEP498 有一个向后移植 Python <3.6

pip install fstring

from fstring import fstring

x = 1

y = 2.0

plus_result = "3.0"

print fstring("{x}+{y}={plus_result}")

# Prints: 1+2.0=3.0

"format" 的字母 f,如 f"hello {somevar}. This little f before the "(双引号)和 {} 字符告诉 python 3,"hey, this string needs to be formatted. So put these variable in there and format it.".

希望这是清楚的。