f-strings中表达式花括号内的等号(=)是什么作用?

66
在Python f-strings中,使用{}的方法是众所周知的,它可以执行代码并将结果以字符串格式呈现(一些教程在这里)。但是,表达式末尾的“=”表示什么意思?

Python f-strings中的{}用于替换值。 =后面的表达式计算要替换的值。

log_file = open("log_aug_19.txt", "w") 
console_error = '...stuff...'           # the real code generates it with regex
log_file.write(f'{console_error=}')

1
我建议查看这篇 Python 3.8中f-string调试 博客。 - Abdul Niyas P M
5个回答

98
这实际上是Python 3.8的全新特性
引入了=格式说明符到f-string。像f'{expr=}'这样的f-string将会扩展为表达式的文本,一个等号,然后是计算表达式的表示形式。
基本上,它方便了频繁使用print调试的情况,因此,我们通常需要编写:
f"some_var={some_var}"

我们现在可以写成:
f"{some_var=}"

因此,作为演示,我们将使用一个闪亮新的Python 3.8.0 REPL:

>>> print(f"{foo=}")
foo=42
>>>

跟进问题:有没有办法将此功能与字典和复杂结构的漂亮打印结合起来? - undefined

11

从 Python 3.8 开始,f-strings 支持“自文档表达式”,主要用于打印调试信息。来自官方文档

Added an = specifier to f-strings. An f-string such as f'{expr=}' will expand to the text of the expression, an equal sign, then the representation of the evaluated expression. For example:

user = 'eric_idle'
member_since = date(1975, 7, 31)
f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"

The usual f-string format specifiers allow more control over how the result of the expression is displayed:

>>> delta = date.today() - member_since
>>> f'{user=!s}  {delta.days=:,d}'
'user=eric_idle  delta.days=16,075'

The = specifier will display the whole expression so that calculations can be shown:

>>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
theta=30  cos(radians(theta))=0.866

9
这是在Python 3.8中引入的。它有助于在编写代码时减少很多f'expr = {expr}。您可以在Python 3.8的新功能文档中查看。 Raymond Hettinger在他的推特上展示了一个很好的例子:
>>> from math import radians, sin
>>> for angle in range(360):
        print(f'{angle=}\N{degree sign} {(theta:=radians(angle))=:.3f}')
angle=0° (theta:=radians(angle))=0.000
angle=1° (theta:=radians(angle))=0.017
angle=2° (theta:=radians(angle))=0.035
angle=3° (theta:=radians(angle))=0.052
angle=4° (theta:=radians(angle))=0.070
angle=5° (theta:=radians(angle))=0.087
angle=6° (theta:=radians(angle))=0.105
angle=7° (theta:=radians(angle))=0.122
angle=8° (theta:=radians(angle))=0.140
angle=9° (theta:=radians(angle))=0.157
angle=10° (theta:=radians(angle))=0.175
...

您还可以查看this,了解为什么首先提出此建议的基本思想。


3

f'{a_string=}'并不完全等同于f'a_string={a_string}'

前者会转义特殊字符,而后者则不会。

e.g:

    a_string = 'word 1 tab \t double quote \\" last words'
    print(f'a_string={a_string}')
    print(f'{a_string=}')

获取:

    a_string=word 1 tab      double quote \" last words
    a_string='word 1 tab \t double quote \\" last words

我刚刚意识到两者的区别在于后者打印了repr,而前者只是打印值。因此,更准确地说应该是: f'{a_string=}'f'a_string={a_string!r}'相同,并允许格式化规范。

1

此处所述:

从Python 3.8开始,允许在f-string中使用等号。这使您可以在输出被评估的表达式的同时快速评估表达式。这对于调试非常方便。

这意味着它将在f-string括号中运行代码的执行,并在末尾添加结果与等号。

因此,它实际上意味着:

"something={executed something}"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接