Evaluation of variable as f-string
Antoon Pardon
antoon.pardon at vub.be
Wed Jan 25 13:26:47 EST 2023
Op 23/01/2023 om 17:24 schreef Johannes Bauer:
> Hi there,
>
> is there an easy way to evaluate a string stored in a variable as if
> it were an f-string at runtime?
>
> I.e., what I want is to be able to do this:
>
> x = { "y": "z" }
> print(f"-> {x['y']}")
>
> This prints "-> z", as expected. But consider:
>
> x = { "y": "z" }
> s = "-> {x['y']}"
> print(s.format(x = x))
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> KeyError: "'y'"
>
> Even though
>
> s = "-> {x}"
> print(s.format(x = x))
>
> Prints the expected "-> {'y': 'z'}".
>
I am probably missing something but is there a reason why the following
wouldn't do what you want:
x = { "y": "z" }
s = "-> {target}"
print(s.format(target = x['y']))
More information about the Python-list
mailing list