= (equal) 在表达式大括号内的 f 字符串中做什么? [英] What does = (equal) do in f-strings inside the expression curly brackets?
问题描述
众所周知,{} 在 Python f-strings 中的用法是执行代码段并以 string
格式给出结果(一些教程此处).但是,表达式末尾的="是什么意思?
log_file = open("log_aug_19.txt", "w")console_error = '...stuff...' # 真正的代码是用正则表达式生成的log_file.write(f'{console_error=')
这实际上是一个 Python 3.8 的全新功能.
<块引用>向 f 字符串添加了 =
说明符.一个 f 字符串,例如 f'{expr='
将扩展到表达式的文本,一个等号,然后求值表达式的表示.
本质上,它促进了打印调试的频繁用例,因此,而我们通常必须编写:
f"some_var={some_var}"
我们现在可以写:
f"{some_var=}"
因此,作为演示,使用全新的 Python 3.8.0 REPL:
<预><代码>>>>打印(f{foo =}")富=42>>>The usage of {} in Python f-strings is well known to execute pieces of code and give the result in string
format (some tutorials here). However, what does the '=' at the end of the expression mean?
log_file = open("log_aug_19.txt", "w")
console_error = '...stuff...' # the real code generates it with regex
log_file.write(f'{console_error=}')
This is actually a brand-new feature as of Python 3.8.
Added an
=
specifier to f-strings. An f-string such asf'{expr=}'
will expand to the text of the expression, an equal sign, then the representation of the evaluated expression.
Essentially, it facilitates the frequent use-case of print-debugging, so, whereas we would normally have to write:
f"some_var={some_var}"
we can now write:
f"{some_var=}"
So, as a demonstration, using a shiny-new Python 3.8.0 REPL:
>>> print(f"{foo=}")
foo=42
>>>
这篇关于= (equal) 在表达式大括号内的 f 字符串中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!