Building complex strings with f-strings
Creating complex strings is, in many ways, the polar opposite of parsing a complex string. We generally find that we use a template with substitution rules to put data into a more complex format.
Getting ready
Let's say we have pieces of data that we need to turn into a nicely formatted message. We might have data that includes the following:
>>> id = "IAD"
>>> location = "Dulles Intl Airport"
>>> max_temp = 32
>>> min_temp = 13
>>> precipitation = 0.4
And we'd like a line that looks like this:
IAD : Dulles Intl Airport : 32 / 13 / 0.40
How to do it...
- Create an
f-string
from the result, replacing all of the data items with{}
placeholders. Inside each placeholder, put a variable name (or an expression.) Note that the string uses the prefix off'
. Thef
prefix creates a sophisticated string object where values are interpolated...