python - 使用 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,我很想看看是否有办法以这种方式使用它;定义模板并在需要时替换为适当的值,而不是立即评估大括号的内容。
解决方案
不,您不能存储 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"))
推荐阅读
- javascript - 我的 AsyncSelect 无法传递在我的 api 中发布的值
- javascript - if条件下如何替换return?
- postgresql - 从 PostgreSQL 的 PROCEDURE 内部调用 FUNCTION
- r - R:你可以从源文件中包含的函数引用服务器或全局环境中的反应变量而不作为参数传递吗?
- core-data - 为什么我的父项目列表在不添加项目的情况下增长
- node.js - 将 Node、Express 和 MongoDB 服务器部署到 heroku
- oracle - ora-01031: 创建第一个用户时权限不足
- jquery - 使用 jQuery 将唯一的类添加到类似的类组
- python - Python,scipy:集成依赖于低级可调用的低级可调用
- javascript - 如何使用 JavaScript 接受用户在控制台中的输入?