gpt4 book ai didi

python - 使用 f 字符串作为模板

转载 作者:行者123 更新时间:2023-12-02 19:50:24 25 4
gpt4 key购买 nike

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

最佳答案

不,您不能存储用于延迟计算的 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"))

关于python - 使用 f 字符串作为模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58302000/

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