3

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}'")
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Hrabal
  • 2,403
  • 2
  • 20
  • 30
  • Is `a.format(**locals())` sufficient? – wim Jun 27 '17 at 12:42
  • yes it is, so it is a.map_format(locals()), I'm just playing around and studying f-strings and see what they can do, haw they can be used.. – Hrabal Jun 27 '17 at 14:38

1 Answers1

2

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253