首页 > 解决方案 > 使用 f 字符串作为模板

问题描述

以前,我使用str.format()过模板方法,例如:

template = "Hello, my name is {0} and I'm {1} years old, my favourite colour is {2}"

# Rest of the program...

print(template.format("John", "30", "Red"))

我最近了解了 f-strings,我很想看看是否有办法以这种方式使用它;定义模板并在需要时替换为适当的值,而不是立即评估大括号的内容。

标签: pythonpython-3.xf-string

解决方案


不,您不能存储 f 字符串以进行延迟评估。

您可以将其包装在 lambda 中,但这实际上不再是 imo 可读的:

template = lambda *, name, age, colour: f"Hello, my name is {name} and I'm {age} years old, my favourite colour is {colour}"
# ...
print(template(name="John", age="30", colour="Red"))

推荐阅读