The f-strings actually use exactly the same formatting markups as the method .format
-
In the .format
the markers :
or !
indicate the beginning of the formatting markup - and what goes before these signs may be blank, be the position or name of the argument in the format. In the example you put, for example:
print("{0:3},{1:5}".format(12,54))
indicates that the first number will use 3 spaces, right-aligned, and the second number 5 spaces, left-aligned.
It’s a pretty bad example, but the equivalent of this with f-strings is simply f"{12:3}, {54:5}"
.
If these values were in variables, this becomes more visible:
hora = 12
minutos = 54
# com format:
print("{0:3}:{1:54}".format(hora, minutos))
# com f-strings:
print(f"{hora:3}:{minutos:5}")
Similarly, all markings for floating point number formatting, alignment, other characters filling that work with the .format
work exactly the same way with f-strings:
f"Preço com juros: R${123.55 * 1.13:.02f}"
- limits the number to every two decimal places.
So much so that there is no separate documentation for formatting f-strings, why should the same existing documentation be used for the method .format
: https://www.python.org/dev/peps/pep-3101/
In addition to the specifiers ":" and "!" to start formatting, from Pthon 3.8, the f-strings also support the "=" sign to help debug - in addition to the value, the "=" sign also prints the expression between the keys:
In [108]: hora = 12
In [109]: print(f"{hora=}")
hora=12