gpt4 book ai didi

python - 如何推迟/延迟 f 字符串的评估?

转载 作者:行者123 更新时间:2023-11-28 19:05:07 25 4
gpt4 key购买 nike

我正在使用模板字符串生成一些文件,我喜欢新的 f-strings 的简洁性,用于减少我以前的模板代码,如下所示:

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}

最佳答案

将字符串评估为 f 字符串(具有其全部功能)的简洁方法是使用以下函数:

def fstr(template):
return eval(f"f'{template}'")

然后你可以这样做:

template_a = "The current name is {name}"
names = ["foo", "bar"]
for name in names:
print(fstr(template_a))
# The current name is foo
# The current name is bar

而且,与许多其他建议的解决方案相比,您还可以:

template_b = "The current name is {name.upper() * 2}"
for name in names:
print(fstr(template_b))
# The current name is FOOFOO
# The current name is BARBAR

关于python - 如何推迟/延迟 f 字符串的评估?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47869722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com