最佳答案
我使用模板字符串来生成一些文件,我喜欢新的 f 字符串的简洁性,因为它可以减少我以前的模板代码,比如:
template_a = "The current name is {name}"
names = ["foo", "bar"]
for name in names:
print (template_a.format(**locals()))
现在我可以这样做,直接替换变量:
names = ["foo", "bar"]
for name in names:
print (f"The current name is {name}")
但是,有时候在其他地方定义模板是有意义的,比如在代码中更高的位置,或者从文件或其他地方导入模板。这意味着模板是一个静态字符串,其中包含格式标记。字符串必须发生一些事情,才能告诉解释器将字符串解释为一个新的 f 字符串,但我不知道是否存在这样的事情。
有没有什么方法可以引入一个字符串并将其解释为 f 字符串以避免使用 .format(**locals())
调用?
理想情况下,我希望能够像这样编码... ... (magic_fstring_function
是我不理解的部分进来的地方) :
template_a = f"The current name is {name}"
# OR [Ideal2] template_a = magic_fstring_function(open('template.txt').read())
names = ["foo", "bar"]
for name in names:
print (template_a)
... 带有所需的输出(不读取文件两次) :
The current name is foo
The current name is bar
但我得到的实际输出是:
The current name is {name}
The current name is {name}