Search code examples
pythonpython-3.6f-string

Build f-strings from normal strings


I'm trying the new f-strings, and I'm wondering if it's possible to "compile" a normal string into an f-string. So to have control on the evaluation time of the f-string, and be capable of defining f-strings before consuming them.

Example pseudo-code:

a = 'normal string with some curly {inside}'
inside = 'in it!'
print(a.make_f_string())
>>> 'normal string with some curly in it!'

So basically my need is to define the f-string before the variable that it contains. or make a string an f-string.

I tried to play with the nesting capabilities of them (SO) but with no luck.

Is it possible? So far the only way I found is with eval(), and seems far from a good way to do it.

eval(f"f'{a}'")

Solution

  • Is it possible?

    No, apart from evaling or execing in a similar fashion, you can't do this.

    Since you are trying to define a format before actual formatting is needed, you need .format, not f-strings.