T0MM91
T0MM91

Reputation: 19

Python3: Replacing fields using .format() "{1:>2}"

Just a quick one really, I am learning Python3 at the moment and saw this {1:>2} used for a replacement field. I was wondering if someone might be able to explain what it is doing here:

for i in range(2, 13):
    for j in range(1, 13):
        print("{1:>2} times {0} is {2}".format(i, j, i * j))
    print("=" * 20)

Is it essentially stating that i>j?

Upvotes: 0

Views: 57

Answers (1)

AlanK
AlanK

Reputation: 9833

:>2 is used for adding padding to the left side

print("{1:>2} times {0} is {2}".format(i, j, i * j))

Your message is:

{1:>2} times {0} is {2}".format(i, j, i * j)

The indexes are as follows:

0 = i
1 = j
2 = i * j

If the statement was:

{1} times {0} is {2}".format(i, j, i * j)

it would evaluate to

j times i is i * j

the :>2 is what's adding the padding -- notice your print are all nicely formatted:

====================
 9 times 4 is 36
10 times 4 is 40

as opposed to this:

====================
9 times 12 is 108
10 times 12 is 120

Upvotes: 2

Related Questions