Formatted String Literals

Formatted String Literals#

String interpolation#

The process where a placeholder in a string is replaced by the contents of a variable is known as string interpolation or variable interpolation.

At long last it’s time to let the obligatory “hello world” program enter the stage and show some of its multiple faces.

name = "world"
print("Hello " + name)  # prints "Hello world"

Instead of using the + operator for the string concatenation, one can also call print() with multiple arguments, which will be separated with a whitespace.

name = "world"
print("Hello", name)    # prints "Hello world"

Python still supports the % format specifier for string interpolation, although this printf-style string formatting is no longer recommended.

name = "world"
print("Hello %s" % (name))  # no longer recommended in Python 3+

Python 3 introduced the str.format() method for string formatting. The {} placeholder will be replaced with the contents of the format argument.

name = "world"
print("Hello {}".format(name))     # prints "Hello world"
print("Hello {n}".format(n=name))  # prints "Hello world" using a named replacement field

Python 3.6 announced the support of the so-called f-strings or formatted string literals, bringing the currently recommended syntax for string formatting and variable interpolation.

name = "world"
print(f"Hello {name}")  # prints "Hello world"

f-string expressions#

Note

The following examples use pi, which is understood to have been imported with from math import pi.

The canonical usecase of f-strings is basic string interpolation,

>>> print(f"pi = {pi}")
pi = 3.141592653589793

or evaluation of expressions.

>>> print(f"pi/2 = {pi/2}")
pi/2 = 1.5707963267948966

Python 3.8+ even supports the following shorthand notation to print the name of a variable and its contents.

>>> print(f"{pi/2 = }")
pi/2 = 1.5707963267948966

Sometimes one has to work with long strings that do not fit on a single line of code. As Python ignores line breaks inside pairs of brackets, the following is a common way to split a long string across multiple lines.

multiline_string = (
    f"Lorem ipsum dolor sit amet, "
    f"consectetur adipiscing elit, "
    f"sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
)

Note how each line is a separate f-string and that all whitespace must be added explicitly to the string.