如果您想打印一个预配置的多行文本块,只需向其中添加一些值(有点像在 Word 中进行邮件合并),您可以使用 str.format 方法。
>>> help(str.format)
format(...)
| S.format(*args, **kwargs) -> str
|
| Return a formatted version of S, using substitutions from args and kwargs.
| The substitutions are identified by braces ('{' and '}').
多行字符串有"""(或者,不太常见的是''')。
template = """{name} is a {role}.
Age: {age}
Height: {height} metres
Weight: {weight} milligrams"""
gabh = template.format(
name="Gabh",
role="Musician",
age=21,
height=5.4,
weight=47
)
print(gabh)
(这与 f-strings 略有不同,后者在创建字符串时将值放入字符串中。)
如果您的字典的键与模板字符串中的{stuff} in {curly braces} 匹配,则可以使用format_map:
template = """{name} is a {role}.
Age: {age}
Height: {height} metres
Weight: {weight} milligrams"""
gabh = {
"name": "Gabh",
"role": "Musician",
"age": 21,
"height": 5.4,
"weight": 47,
}
print(template.format_map(gabh))