且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从普通字符串构建F字符串

更新时间:2023-10-31 14:32:16

有可能吗?

否,除了以类似方式进行evalexec ing外,您不能执行此操作.

由于要在需要实际格式化之前尝试定义格式,因此需要.format而不是f字符串.

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}'")

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.