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}'")
2
  • Is a.format(**locals()) sufficient? Commented Jun 27, 2017 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.. Commented Jun 27, 2017 at 14:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.