3.3.5. Including variable contents in strings using f-strings#
We often use strings to report results. For instance, we could print a calculated ankle moment to the console using two print
calls:
ankle_moment = 100.1 # (for instance)
print("The calculated moment at the ankle in Nm is:")
print(ankle_moment)
The calculated moment at the ankle in Nm is:
100.1
A single string that includes both the definition and the result would be more readable:
“The calculated ankle moment is 100.1 Nm.”
Including variables into strings is easily done using f-strings. The name “f-strings” comes from their f
prefix. With f-strings, Python evaluates the result of any instruction placed between curly braces {}
:
# Here, we create the sentence above.
the_string = (
f"The calculated ankle moment is {ankle_moment} Nm."
)
# And here, we print it.
print(the_string)
The calculated ankle moment is 100.1 Nm.
When an f-string contains a float, we can print it to a given precision, using :.xf
just after the expression in braces, where x
is the number of digits after the decimal point. For instance:
print(f"The calculated ankle moment is {ankle_moment:.0f} Nm.")
print(f"The calculated ankle moment is {ankle_moment:.2f} Nm.")
print(f"The calculated ankle moment is {ankle_moment:.5f} Nm.")
The calculated ankle moment is 100 Nm.
The calculated ankle moment is 100.10 Nm.
The calculated ankle moment is 100.10000 Nm.