Evaluation of variable as f-string

Christian Gollwitzer auriocus at gmx.de
Fri Jan 27 17:10:52 EST 2023


Am 27.01.23 um 21:43 schrieb Johannes Bauer:
> I don't understand why you fully ignore literally the FIRST example I 
> gave in my original post and angrily claim that you solution works when 
> it does not:
> 
> 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.


(base) Apfelkiste:Abschlussmeeting chris$ ipython
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: x = { "y": "z" }

In [2]: s = "-> {x[y]}"

In [3]: print(s.format(x = x))
-> z

In [4]:

	Christian


More information about the Python-list mailing list