为什么 f 字符串在引用的变量发生变化时不发生变化? [英] Why don't f-strings change when variables they reference change?
问题描述
在最近的 Python 3.6 版本中使用新的 f-strings 时,我注意到以下几点:
我们创建一个
<预><代码>>>>foo = '酒吧'foo
变量,值为bar
:然后,我们声明一个新变量,它是我们的 f 字符串,它应该需要
<预><代码>>>>baz = f'坚持{foo}'foo
进行格式化:好的,一切顺利,然后我们调用
<预><代码>>>>巴兹'坚持在酒吧'baz
来检查它的值:让我们尝试改变
<预><代码>>>>foo = '垃圾邮件'>>>巴兹'坚持在酒吧'foo
的值并再次调用baz
:
不应该是动态的吗?为什么会发生这种情况?我认为如果 foo
的值发生变化,f-string 会更新,但这并没有发生.我不明白这是如何工作的.
f-string
在您执行时已经被评估:
具体来说,它查找名称 foo
的值并将其替换为 'bar'
,即为它找到的值.baz
然后包含格式化后的字符串.
f-string
s 不是常数;意思是,它们内部没有替换字段等待评估.当你执行它们时它们会评估,之后,分配的值只是一个普通的字符串:
有关参考,请参阅有关格式化的部分字符串文字:
<块引用>[..] 虽然其他字符串文字总是有一个常量值,但格式化的字符串实际上是在运行时计算的表达式.[..]
在执行表达式(查找替换字段及其后续格式)之后,它们没有什么特别之处,表达式已被评估为字符串并分配给 baz
.
While playing with new f-strings in the recent Python 3.6 release, I've noticed the following:
We create a
foo
variable with valuebar
:>>> foo = 'bar'
Then, we declare a new variable, which is our f-string, and it should take
foo
to be formatted:>>> baz = f'Hanging on in {foo}'
Ok, all going fine and then we call
baz
to check its value:>>> baz 'Hanging on in bar'
Let's try to change the value of
foo
and callbaz
again:>>> foo = 'spam' >>> baz 'Hanging on in bar'
Shouldn't it be dynamic? Why does this happen? I thought the f-string would update if the value of foo
changed, but this didn't happened. I don't understand how this works.
The f-string
has already been evaluated when you executed:
>>> baz = f'Hanging on in {foo}'
Specifically, it looked up the value for the name foo
and replaced it with 'bar'
, the value that was found for it. baz
then contains the string after it has been formatted.
f-string
s aren't constant; meaning, they don't have a replacement field inside them waiting for evaluation after being evaluated. They evaluate when you execute them, after that, the assigned value is just a normal string:
>>> type(f'hanging on in {foo}')
<class 'str'>
For reference, see the section on Formatted String Literals:
[..] While other string literals always have a constant value, formatted strings are really expressions evaluated at run time. [..]
After the expression (the look-up for the replacement field and its consequent formatting) is performed, there's nothing special about them, the expression has been evaluated to a string and assigned to baz
.
这篇关于为什么 f 字符串在引用的变量发生变化时不发生变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!