Why don't f-strings change when variables they reference change?

前端 未结 2 1549
太阳男子
太阳男子 2021-01-11 18:47

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

2条回答
  •  无人及你
    2021-01-11 19:34

    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}')
    
    

    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.

提交回复
热议问题