Search code examples
pythonf-string

Consider a String a f-string in Python


Suppose I have

x = 3 
s = "f'12{x}4'"

How to consider s as f-string to print 1234, like writing print(f'12{x}4') when I print s, it prints it as it as: f'12{x}4'


Solution

  • Assuming you ask this because you can not use actual f-strings, but also don't want to pass the parameters explicitly using format, maybe because you do not know which parameter are in the not-really-an-f-string, and also assuming you don't want to use eval, because, well, eval.

    You could pass the variables in the locals or globals scope to format:

    >>> x = 3
    >>> s = '12{x}4'
    >>> s.format(**globals())
    '1234'
    >>> s.format(**locals())
    '1234'
    

    Depending on where s is coming from (user input perhaps?) This might still be a bit risky, though, and it might be better to define a dict of "allowed" variables and use that in format. As with globals and locals, any unused variables do not matter.

    >>> vars = {"x": x, "y": y, "z": z}
    >>> s.format(**vars)
    

    Note that this does not give you the full power of f-strings, though, which will also evaluate expressions. For instance, the above will not work for s = '12{x*x}4'.