python-3.6中带有'f'前缀的字符串 [英] String with 'f' prefix in python-3.6

查看:27
本文介绍了python-3.6中带有'f'前缀的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试用 Python 3.6.通过新代码,我偶然发现了这种新语法:

f"我的格式化字符串!"

似乎我们可以这样做:

<预><代码>>>>姓名 = "乔治">>>print(f"我很酷的字符串叫做{name}.")我很酷的字符串叫做乔治.

谁能解释一下它的内部运作方式?特别是 f 前缀字符串可以采用的变量范围是什么?

解决方案

参见 PEP 498 文字字符串插值:

<块引用>

从字符串中提取的表达式在 f 字符串出现的上下文中进行计算.这意味着表达式可以完全访问局部和全局变量.可以使用任何有效的 Python 表达式,包括函数和方法调用.

所以表达式的计算就像它们出现在同一个作用域中一样;局部变量、闭包和全局变量的工作方式与同一上下文中的其他代码相同.

您可以在参考文档中找到更多详细信息:

<块引用>

格式化字符串文字中的表达式被视为用括号括起来的正则 Python 表达式,但有一些例外.不允许使用空表达式,并且 lambda 表达式必须用显式括号括起来.替换表达式可以包含换行符(例如在三引号字符串中),但不能包含注释.每个表达式都在出现格式化字符串文字的上下文中按从左到右的顺序进行计算.

由于您正在尝试 3.6 alpha 版本,请务必阅读 Python 3.6 的新增功能 文档.它总结了所有更改,包括指向相关文档和 PEP 的链接.

需要说明的是:3.6 还没有发布;第一个 alpha 版本预计要到 2016 年 5 月才会发布.请参阅 3.6 发布时间表.>

I'm trying out Python 3.6. Going through new code, I stumbled upon this new syntax:

f"My formatting string!"

It seems we can do things like this:

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

Can anyone shed some light on the inner workings of this? In particular what is the scope of the variables that an f-prefixed string can take?

解决方案

See 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.

So the expressions are evaluated as if they appear in the same scope; locals, closures, and globals all work the same as in other code in the same context.

You'll find more details in the 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.

Since you are trying out a 3.6 alpha build, please do read the What's New In Python 3.6 documentation. It summarises all changes, including links to the relevant documentation and PEPs.

And just to be clear: 3.6 isn't released yet; the first alpha is not expected to be released until May 2016. See the 3.6 release schedule.

这篇关于python-3.6中带有'f'前缀的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆