Build f-strings from normal strings

烈酒焚心 提交于 2020-01-04 06:36:06

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/44780515/build-f-strings-from-normal-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!