Dev*_*ark 52 python scope string-formatting python-3.6 f-string
我正在尝试使用Python 3.6.通过新代码,我偶然发现了这个新语法:
f"My formatting string!"
Run Code Online (Sandbox Code Playgroud)
看来我们可以这样做:
>>> name = "George"
>>> print(f"My cool string is called {name}.")
My cool string is called George.
Run Code Online (Sandbox Code Playgroud)
任何人都可以对这个内部运作有所了解吗?特别是f前缀字符串可以采用的变量范围是多少?
Mar*_*ers 43
参见PEP 498 Literal String Interpolation:
从字符串中提取的表达式在f字符串出现的上下文中计算.这意味着表达式具有对本地和全局变量的完全访问权限.可以使用任何有效的Python表达式,包括函数和方法调用.
因此表达式被评估为好像它们出现在同一范围内; locals,closures和globals的工作方式与同一上下文中的其他代码相同.
您可以在参考文档中找到更多详细信息:
格式化字符串文字中的表达式被视为由括号括起来的常规Python表达式,但有一些例外.不允许使用空表达式,并且
lambda表达式必须由显式括号括起.替换表达式可以包含换行符(例如,在三引号字符串中),但它们不能包含注释.每个表达式在格式化字符串文字出现的上下文中按从左到右的顺序进行计算.
由于您正在尝试3.6 alpha版本,请阅读Python 3.6中的新功能文档.它总结了所有更改,包括相关文档和PEP的链接.
而仅仅是明确的:3.6没有被释放尚未 ; 第一个alpha预计将在2016年5月之前发布.请参阅3.6发布计划.
f字符串还支持花括号内的所有Python表达式。
print(f"My cool string is called {name.upper()}.")
Run Code Online (Sandbox Code Playgroud)
小智 6
值得注意的是,这个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
Run Code Online (Sandbox Code Playgroud)