String Formatting
Learn how Python's f-strings enable dynamic string formatting by interpolating variables and expressions into template text.
We'll cover the following
Overview
Python 3 has powerful string formatting and templating mechanisms that allow us to construct strings comprised of template text and interspersed representations of objects usually from variables, but also from expressions. We’ve used it in many previous examples, but it is much more versatile than the simple formatting specifiers we’ve used.
A format string (also called an f-string) has a prefix on the opening quotation mark of f
, as in f"hello world"
. If such a string contains the special characters {
and }
, expressions, including variables from the surrounding scope, are evaluated and then interpolated into the string.
If we run the statements given in the example below, it replaces the braces with variables, in order:
Get hands-on with 1400+ tech skills courses.