我正在使用模板字符串来生成一些文件,我喜欢为此目的的新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) 我有一个字符串,我想要花括号,但也利用f字符串功能.是否有一些适用于此的语法?
这有两种方法不起作用.我想将文字文本" {bar}
"包含在字符串中.
foo = "test"
fstring = f"{foo} {bar}"
Run Code Online (Sandbox Code Playgroud)
NameError:未定义名称"bar"
fstring = f"{foo} \{bar\}"
Run Code Online (Sandbox Code Playgroud)
SyntaxError:f-string表达式部分不能包含反斜杠
期望的结果:
'test {bar}'
Run Code Online (Sandbox Code Playgroud)
编辑:看起来这个问题有相同的答案如何在python字符串中打印文字大括号字符,并使用.format吗?,但你只能知道,如果你知道格式函数使用与f字符串相同的规则.所以希望这个问题对于将f-string搜索者与这个答案联系起来是有价值的.