How do I convert a string into an f-string?

f-strings are code. Not just in the safe, “of course a string literal is code” way, but in the dangerous, arbitrary-code-execution way. This is a valid f-string:

f"{__import__('os').system('install ransomware or something')}"

and it will execute arbitrary shell commands when evaluated.

You’re asking how to take a string loaded from a text file and evaluate it as code, and the answer boils down to eval. This is of course a security risk and probably a bad idea, so I recommend not trying to load f-strings from files.

If you want to load the f-string f"My name is {name} and I am {age} years old" from a file, then actually put

f"My name is {name} and I am {age} years old"

in the file, f and quotation marks and all.

Read it from the file, compile it and save it (so eval doesn’t have to recompile it every time):

compiled_fstring = compile(fstring_from_file, '<fstring_from_file>', 'eval')

and evaluate it with eval:

formatted_output = eval(compiled_fstring)

If you do this, be very careful about the sources you load your f-strings from.

Leave a Comment