Evaluation of variable as f-string

Johannes Bauer dfnsonfsduifb at gmx.de
Fri Jan 27 15:33:32 EST 2023


Am 25.01.23 um 20:38 schrieb Thomas Passin:

>> x = { "y": "z" }
>> s = "-> {target}"
>> print(s.format(target = x['y']))
> 
> Stack overflow to the rescue:

No.

> 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"

Great.

s = '"""'

 > def effify(non_f_str: str):
 >      return eval(f'f"""{non_f_str}"""')
 >
 > print(effify(s))  # prints as expected: "-> z"

 >>> print(effify(s))
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<stdin>", line 2, in effify
   File "<string>", line 1
     f"""""""""
            ^
SyntaxError: unterminated triple-quoted string literal (detected at line 1)

This is literally the version I described myself, except using triple 
quotes. It only modifies the underlying problem, but doesn't solve it.

Cheers,
Johannes


More information about the Python-list mailing list