Format Specifications#

Often it’s not sufficient to simply print the contents of a variable. In addition one has to be able to control how the values are being presented, for instance how many digits of a decimal number should be visible. The format specification mini-language provides a powerful and yet flexible handle on string formatting.

Note

We use f-strings in all examples, but the format specifiers also work with the format() string method.

Formatting of strings#

Strings can be represented with a minimal length, text alignment and padding.

>>> print(f"=== {'xxx':10} ===")
=== xxx        ===
>>> print(f"=== {'xxx':<10} ===")
=== xxx        ===
>>> print(f"=== {'xxx':^10} ===")
===    xxx     ===
>>> print(f"=== {'xxx':>10} ===")
===        xxx ===
>>> print(f"=== {'xxx':.^10} ===")
=== ...xxx.... ===

Formatting of numbers#

Numbers can be represented with a fixed width, precision (number of decimal places) and padding.

>>> print(f"pi = {pi:.5f}")
pi = 3.14159
>>> print(f"pi = {pi:9.5f}")
pi =   3.14159
>>> print(f"pi = {pi:09.5f}")
pi = 003.14159

One can force the use of scientific notation with e or E separator and a given precision,

>>> print(f"{pi:e}")
3.141593e+00
>>> print(f"{pi:.3E}")
3.142E+00

or use the g general format specifier to dynamically switch between fixed precision and scientific notation, depending on the magnitude of the number.

>>> print(f"{1.23456:.4g}")
1.235
>>> print(f"{1234.56:.4g}")
1235
>>> print(f"{12345.6:.4g}")
1.235e+04

Large numbers can also be represented with a comma as thousands separator.

>>> print(f"{1234567890:,}")
1,234,567,890

By default, the sign of a number is only shown if it is negative. This behavior can also be customized, either with + to always output the sign, or with to output a leading space for positive numbers.

>>> print(f"{pi:+.5f}")
+3.14159
>>> print(f"{pi: .5f}")
 3.14159

A numeric value can be represented in different bases.

>>> n = 42; print(f"decimal {n:d} = hexadecimal {n:x} = binary {n:b}")
decimal 42 = hexadecimal 2A = binary 101010

Formatting of dates and times#

Let now be the current date and time as returned by datetime of the standard library.

import datetime

now = datetime.datetime.now()

Various format specifiers can be used to customize its representation.

>>> print(f"{now: %d/%m/%Y %H:%M:%S}")
27/10/2021 10:26:33
>>> print(f"{now: %F}")
2021-10-27
>>> print(f"{now: %A}")
Wednesday

See also

The Python documentation contains the full list of strftime() format codes.