【发布时间】:2017-11-30 12:30:34
【问题描述】:
我正在尝试新的 f 字符串,我想知道是否可以将普通字符串“编译”成 f 字符串。 因此可以控制 f-string 的评估时间,并能够在使用 f-strings 之前对其进行定义。
示例伪代码:
a = 'normal string with some curly {inside}'
inside = 'in it!'
print(a.make_f_string())
>>> 'normal string with some curly in it!'
所以基本上我需要在它包含的变量之前定义 f 字符串。或将字符串设为 f 字符串。
我尝试使用nesting capabilities of them (SO),但没有成功。
有可能吗?到目前为止,我发现的唯一方法是使用 eval(),而且似乎远非一个好方法。
eval(f"f'{a}'")
【问题讨论】:
-
a.format(**locals())足够了吗? -
是的,所以它是 a.map_format(locals()),我只是在玩耍和研究 f-strings,看看它们能做什么,它们可以被使用..
标签: python python-3.6 f-string