Python string format width

I am having problems with replicating the format as shown in the picture:

desired output formatting

my results:

current output formatting

I am currently using:

print '{}.{:<20} {}.'.format(i,'sum so far:',sum)

      

I've tried left, right and center alignment, but I just can't get the format I want.

+3


source to share


2 answers


You can do the line alignment of the item number first:



tot = 0 
for i in xrange(1, 11):
    tot += i
    print '{:<20}{} {}.'.format(str(i) + '.',  'sum so far:', tot)

      

0


source


First convert all of the header including '.'

to a string so you can calculate the width including it.



>>> '{:<20} sum so far: {}.'.format('{}.'.format(9), 123)
'9.                   sum so far: 123.'
>>> '{:<20} sum so far: {}.'.format('{}.'.format(10), 123)
'10.                  sum so far: 123.'

      

+2


source







All Articles