If you'd like to have a preconfigured multiline block of text to print, and just add some values to it (bit like doing a mail-merge in Word), you can use the str.format
method.
>>> 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 '}').
Multiline strings have """
(or, less commonly, '''
).
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)
(This is slightly different to f-strings, where values get put into the string at the moment it's created.)
If you have a dictionary with keys matching the {stuff} in {curly braces}
in your template string, you can use 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))