我正在使用模板字符串来生成一些文件,我喜欢为此目的的新f字符串的简洁性,以减少我之前的模板代码,如下所示:
template_a = "The current name is {name}"
names = ["foo", "bar"]
for name in names:
print (template_a.format(**locals()))
Run Code Online (Sandbox Code Playgroud)
现在我可以这样做,直接替换变量:
names = ["foo", "bar"]
for name in names:
print (f"The current name is {name}")
Run Code Online (Sandbox Code Playgroud)
但是,有时在其他地方定义模板是有意义的 - 在代码中更高,或从文件或其他东西导入.这意味着模板是一个带有格式标签的静态字符串.必须在字符串上发生一些事情,告诉解释器将字符串解释为新的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)
Run Code Online (Sandbox Code Playgroud)
...使用此期望的输出(不读取文件两次):
The current name is foo
The current name is bar
Run Code Online (Sandbox Code Playgroud)
...但我得到的实际输出是:
The current …Run Code Online (Sandbox Code Playgroud)