使用 f-strings 作为模板

Using f-strings as templates

之前,我使用 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,我很想看看有没有办法以这种方式使用它;定义一个模板并在需要时替换为适当的值,而不是立即评估大括号的内容。

不,您不能存储用于延迟计算的 f 字符串。

您可以将其包装在 lambda 中,但在我看来,这并不能真正提高可读性:

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"))