I was trying a coding challenge and gave up, in the submitted answers for others I found this string formatting method.
number = 10
for i in range(1, number+1):
print("{0:{w}d} {0:{w}o} {0:{w}X} {0:{w}b}".format(i, w=len("{0:b}".format(number))))
The output was:
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
It is correct for the question I just had a few questions. Like for example where did the spaces come from? How do the d,o,X,b format it as int, oct, hex, bin? What is the 0: for? What is that i in the first format doing
So I tried this:
i = 8
print("{0:6b}".format(i))
The output was:
1000
with 2 spaces at the front.
The i here is what is getting turned into binary.
The spaces seem to work like
6 - len(str(bin(i))
then the binary value.
Any help explaining or a link to a Youtube video would be greatly appreciated.
This is a nested format()
implementation:
You can break your code and check:
This w
thing is just 4
number = 10
for i in range(1, number+1):
print(len("{0:b}".format(number)))
#output
4
4
4
4
4
4
4
4
4
4
You can get rid of this by directly using 4:
number = 10
for i in range(1, number+1):
print("{0:4d} {0:4o} {0:4X} {0:4b}".format(i))
#output
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
4
is used for padding; if you do not use 4
the this will be output:
number = 10
for i in range(1, number+1):
print("{0:d} {0:o} {0:X} {0:b}".format(i))
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
Please go through the format()
documentation for detailed explanation:
https://docs.python.org/3/library/string.html#string.Formatter.format
Here is the snip from the doc: