为什么 f 字符串在引用的变量发生变化时不发生变化? [英] Why don't f-strings change when variables they reference change?

查看:64
本文介绍了为什么 f 字符串在引用的变量发生变化时不发生变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的 Python 3.6 版本中使用新的 f-strings 时,我注意到以下几点:

  1. 我们创建一个 foo 变量,值为 bar:

    <预><代码>>>>foo = '酒吧'

  2. 然后,我们声明一个新变量,它是我们的 f 字符串,它应该需要 foo 进行格式化:

    <预><代码>>>>baz = f'坚持{foo}'

  3. 好的,一切顺利,然后我们调用 baz 来检查它的值:

    <预><代码>>>>巴兹'坚持在酒吧'

  4. 让我们尝试改变foo的值并再次调用baz:

    <预><代码>>>>foo = '垃圾邮件'>>>巴兹'坚持在酒吧'

不应该是动态的吗?为什么会发生这种情况?我认为如果 foo 的值发生变化,f-string 会更新,但这并没有发生.我不明白这是如何工作的.

解决方案

f-string 在您执行时已经被评估:

<预><代码>>>>baz = f'坚持{foo}'

具体来说,它查找名称 foo 的值并将其替换为 'bar',即为它找到的值.baz 然后包含格式化后的字符串.

f-strings 不是常数;意思是,它们内部没有替换字段等待评估.当你执行它们时它们会评估,之后,分配的值只是一个普通的字符串:

<预><代码>>>>类型(f'挂在{foo}')<类'str'>

有关参考,请参阅有关格式化的部分字符串文字:

<块引用>

[..] 虽然其他字符串文字总是有一个常量值,但格式化的字符串实际上是在运行时计算的表达式.[..]

在执行表达式(查找替换字段及其后续格式)之后,它们没有什么特别之处,表达式已被评估为字符串并分配给 baz.

While playing with new f-strings in the recent Python 3.6 release, I've noticed the following:

  1. We create a foo variable with value bar:

    >>> foo = 'bar'
    

  2. 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}'
    

  3. Ok, all going fine and then we call baz to check its value:

    >>> baz
    'Hanging on in bar'
    

  4. Let's try to change the value of foo and call baz 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-strings 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屋!

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