Evaluation of variable as f-string

Thomas Passin list1 at tompassin.net
Wed Jan 25 14:38:38 EST 2023


On 1/25/2023 1:26 PM, Antoon Pardon wrote:
> 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']))

Stack overflow to the rescue:

Search phrase:  "python evaluate string as fstring"

https://stackoverflow.com/questions/47339121/how-do-i-convert-a-string-into-an-f-string

def effify(non_f_str: str):
     return eval(f'f"""{non_f_str}"""')

print(effify(s))  # prints as expected: "-> z"


More information about the Python-list mailing list