gpt4 book ai didi

python - f"{expr=}"是一个新的 f 字符串表达式(见训练大括号前的等号)?从哪个版本的python开始?

转载 作者:行者123 更新时间:2023-12-05 02:01:23 31 4
gpt4 key购买 nike

我收到了一个 python 笔记本,里面充满了像 f"{expr=}" 这样的表达式,在我的环境中会产生错误消息:

var=7

print(f"{var=}")

File "<fstring>", line 1
(var=)
^
SyntaxError: invalid syntax

我怀疑/预计它实际上可能是 f"expr={expr}" 的新语法,即如以下打印语句所示:

print(f"var={var}")

var=7

事实上,我经常使用像后者这样的表达式来进行调试,如果能有一个简写就更好了。

那是不是比我的 (3.7.6) 更高版本的 python?还是 fstring 模块的自定义?在 Web 或 SE 中搜索它没有结果。

如果它不是标准功能,我该如何让它发挥作用?

最佳答案

Answer - Python Version 3.8

f-strings simplified a lot of places where str.format and % style formatting. There was still a place where you want to print a value of the variable or expression and also add some context with the string like variable name or some arbitrary name so that when you have many statements you can differentiate between the printed values. So using variable name followed by value is more common format of print style debugging.BlockquoteThis caused users to write f"name = {name}" and can get unwieldy whenvariable names are long like filtered_data_from_third_party would bewritten as f"filtered_data_from_third_party ={filtered_data_from_third_party}". In those cases we resort to shorternames we understand easily at the context like f"filtered data{filtered_data_from_third_pary}". f-strings also support formatspecifiers so you can write f"{name!r}" which is same asf"{repr(name)}".

Given the above boilerplate an idea was posted in python-ideas arounda format specifier where you can use it and the f-string would expandlike a macro into <variable_name> = <value_of_variable>. Initially !dwas chosen so f"{name!d}" would expand to f"name={repr(name)}". Thiswas initially implemented in bpo36774. After discussion !d was changedto use = with input from Guido and other core devs since there couldbe usecases served by !d in the future and to reserve alphabeticalnames in format-string for other uses. So this was changed to use = asthe notation for this feature in bpo36817. An overview of it’s usageis as below with various features available.

Read more here

关于python - f"{expr=}"是一个新的 f 字符串表达式(见训练大括号前的等号)?从哪个版本的python开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66612440/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com