Evaluation of variable as f-string

Peter J. Holzer hjp-python at hjp.at
Sat Jan 28 08:28:47 EST 2023


On 2023-01-27 20:56:49 -0500, Thomas Passin wrote:
> On 1/27/2023 5:10 PM, Christian Gollwitzer wrote:
> > Am 27.01.23 um 21:43 schrieb Johannes Bauer:
> > > x = { "y": "z" }
> > > s = "-> {x['y']}"
> > > print(s.format(x = x))
> > > Traceback (most recent call last):
> > >    File "<stdin>", line 1, in <module>
> > > KeyError: "'y'"
> > > 
> > > This. Does. Not. Work.
> > 
> > It's because "you're holding it wrong!". Notice the error message; it
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> > says that the key 'y' does not exist.
[...]
> > In [1]: x = { "y": "z" }
> > In [2]: s = "-> {x[y]}"
> > In [3]: print(s.format(x = x))
> > -> z
> > In [4]:
> 
> Oops, that's not quite what he wrote.
> 
> You: s = "-> {x[y]}"    # Works
> Him: s = "-> {x['y']}"  # Fails

That was the point.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20230128/7d5ce35e/attachment.sig>


More information about the Python-list mailing list