Python/Formatted String Literals
[i]Learn· Input and Output

Formatted String Literals

Formatted string literals (also called f-strings for short) let you include the value of Python expressions inside a string by prefixing the string with f or F and writing expressions as {expression}.

An optional format specifier can follow the expression. This allows greater control over how the value is formatted. The following example rounds pi to three places after the decimal:

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

Passing an integer after the ':' will cause that field to be a minimum number of characters wide. This is useful for making columns line up.

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
...
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

Other modifiers can be used to convert the value before it is formatted. '!a' applies ascii(), '!s' applies str(), and '!r' applies repr():

>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

The = specifier can be used to expand an expression to the text of the expression, an equal sign, then the representation of the evaluated expression:

>>> bugs = 'roaches'
>>> count = 13
>>> area = 'living room'
>>> print(f'Debugging {bugs=} {count=} {area=}')
Debugging bugs='roaches' count=13 area='living room'

See self-documenting expressions for more information on the = specifier. For a reference on these format specifications, see the reference guide for the Format specification mini-language.

Source: Input and Output by Python Software Foundation, licensed under PSF-2.0. Retrieved 2026-11-18. Changes: Extracted section 7.1.1 from The Python Tutorial (Python 3.14), https://docs.python.org/3.14/tutorial/inputoutput.html; removed section numbers, permalinks and site navigation; code blocks kept as shown; runnable examples: prompts and output lines removed.