Evaluation of variable as f-string

Rob Cliffe rob.cliffe at btinternet.com
Wed Jan 25 19:58:12 EST 2023



On 25/01/2023 19:38, Thomas Passin wrote:
>
> 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"
Duh!  Am I the only one who feels stupid not thinking of this?
Although of course it won't work if the string already contains triple 
double quotes.
I believe this could be got round with some ingenuity (having the effify 
function parse the string and replace genuine (not embedded in 
single-quotes) triple double quotes with triple single quotes, though 
there are some complications).
And the effify function can't be put in its own module unless it can be 
passed the globals and/or locals dictionaries as needed for eval to 
use.  Something like this:

def effify(non_f_str, glob=None, loc=None):
     return eval(f'f"""{non_f_str}"""',
         glob if glob is not None else globals(),
         loc if loc is not None else locals())

Best wishes
Rob Cliffe


More information about the Python-list mailing list