Formatted printing that replaces the use of . format() in python versions from 3.6 onwards. How to use?

Asked

Viewed 248 times

3

We know that:

"{0}:{1}:{2}".format(hora,minuto, segundo)

is equivalent to:

f"{hora}:{minuto}:{segundo}"

What is the equivalent of the expression below using the notation f" " ?

print("{0:3},{1:5}".format(12,54))

I made several attempts but it did not work. It is possible to replace any ". fornmat()" with the notation f" " ?

What if it was a floating point print and needed to specify the accuracy? What would it be like with the f notation" "?

1 answer

5


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.