How to print binary numbers using f"" string instead of .format()?
Here is my take:
In the old .format()
the 0 represented the 1st element passed to the format function. "{0:>2} in binary is {0:>08b}".format(i)
. 0 was used twice to access the first variable twice. Another way of writing it would be: "{:>2} in binary is {:>08b}".format(i,i)
omitting the indices.
In the new f''
format we pass variables/expressions instead.
Your f-string should have expressions in it rather than indices:
f'{i:>2} in binary is {i:>08b}'
Anywhere you had 0
in the original format string should be replaced by the actual first argument: in this case i
.
Caveat
The expression in the f-string is evaluated twice, but the argument to format
is only evaluated once when you access it by index. This matters for more complicated expressions. For example:
"{0:>2} in binary is {0:>08b}".format(i + 10)
Here the addition i + 10
only happens once. On the other hand
f"{i+10:>2} in binary is {i+10:>08b}"
does the addition twice because it is equivalent to
"{:>2} in binary is {:>08b}".format(i + 10, i + 10)
Or
"{0:>2} in binary is {1:>08b}".format(i + 10, i + 10)
The workaround is to pre-compute the results of expressions that appear in your f-string more than once:
j = i + 10
f"{j:>2} in binary is {j:>08b}"
Now j
is evaluated multiple times, but it's just a simple reference.