我正在使用模板字符串生成一些文件,我喜欢新的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字符串,但我不知道是否存在这种情况.
Is there any way to bring in a string and have it interpreted as an f-string to avoid using the 100 call?
理想情况下,我希望能够像这样编码...(其中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}