Taylor
Taylor

Reputation: 13

How do I adjust a string's field length with print formatting?

I'm a beginner and I saw this example I didn't understand in a Udemy Python course:

"Within the curly braces you can assign field lengths, left/right alignments, rounding parameters and more."

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:9}'.format('Apples', 3.))
print('{0:8} | {1:9}'.format('Oranges', 10))

Fruit    | Quantity
Apples   |       3.0
Oranges  |        10

I didn't understand what I was looking at, so I tried playing with the first line like so to figure out the rules:

print('{0:25} | {1:9}'.format('Fruit', 'Quantity'))

Fruit                     | Quantity

Next I tried this:

print('{0:8} | {1:25}'.format('Fruit', 'Quantity'))

Fruit    | Quantity                 

You can't see it but if you highlight the space after Quantity, I seem to have created a length equal to 25 spaces including the word.

Unexpectedly, reducing the number does not delete letters from the words Fruit or Quantity:

print('{0:4} | {1:4}'.format('Fruit', 'Quantity'))

Fruit | Quantity

The next line seems to have different rules affecting the float 3.0 than the string 'Quantity':

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:25}'.format('Apples', 3.))

Fruit    | Quantity 
Apples   |                       3.0

Next I tried reducing the field's length for the float.

print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))
print('{0:8} | {1:1}'.format('Apples', 3.))

Fruit    | Quantity 
Apples   | 3.0

Adjusting this number puts spaces before floats/integers, but adds space to the end of a string if possible. Looking at the 10 in the third line, it seems that the integer appears at the end of the defined number of spaces. That's my guess for what the rules are.

Is there an explanation anywhere online for this technique? There was no further explanation in the course and I didn't know what to search for specifically on Google.

Thanks to anyone who took the time to read all this!

Upvotes: 1

Views: 684

Answers (1)

You got it right. As a general rule strings get aligned to the left, numbers to the right. If the number of characters needed to represent a field exceed the allowed space, it will take the additional space.

You can adjust the alignment of each field using '<' or '>'. For more details check this

Upvotes: 1

Related Questions