Aligning With String Formatting
Solution 1:
As a generalized solution:
Use this format string if you want the right column, center and left column to be aligned right, center and left respectively:
>>> '{0:.<10}{1:.^10}{2:.>10}'.format('GBP', 0.8639, 0.8399) 'GBP.........0.8639......0.8399'# Another example>>> '{0:.<10}{1:.^10}{2:.>10}'.format('GBPTEST', 0.90, 0.8) 'GBPTEST......0.9...........0.8'
OR, this format string if you want all the columns except rightmost column to be aligned right:
>>> '{0:.<10}{1:.>10}{2:.>10}'.format('GBP', 0.8639, 0.8399) 'GBP...........0.8639....0.8399'# Another example>>> '{0:.<10}{1:.>10}{2:.>10}'.format('GBPTEST', 0.90, 0.8) 'GBPTEST..........0.9.......0.8'
OR, this format string if you want all the columns to be aligned left:
>>> '{0:.<10}{1:.<10}{2:<10}'.format('GBP', 0.8639, 0.8399) 'GBP.......0.8639....0.8399 '# Another example>>> '{0:.<10}{1:.<10}{2:<10}'.format('GBPTEST', 0.90, 0.8) 'GBPTEST...0.9.......0.8 '
Change the value of 10 for each param based on the size of column you need.
Below will be the format string specific for the kind of params as mentioned in the question:
>>> '{i:.<10}{e[0]:.^10}{e[1]:.>10}'.format(i='GBP', e=(0.8639, 0.8399))
'GBP.........0.8639......0.8399'# Another example>>> '{i:.<10}{e[0]:.^10}{e[1]:.>10}'.format(i='GBPTEST', e=(0.90, 0.8))
'GBPTEST......0.9...........0.8'
Solution 2:
Increase the last number from 6 to 12.
"{i:.<10}{e[0]:.^6}{e[1]:.>12}".format(i=i, e=e)
This gives you
GBP.......0.8639......0.8399
Solution 3:
Your last two format specs only have a width of 6 and the values themselves are six digits, so there aren't any fill characters. If you want e[0]
centered between i
and e[1]
with six dots on either side, construct the second format spec based on the length of e[0] - and don't specify a width for the other two.
>>>i = 'GPB'>>>e = (0.8639, 0.8399)>>>n = len(str(e[0]))>>>s = '{i:}{e[0]:.^' + str(12+n) + '}{e[1]:}'>>>s
'{i:}{e[0]:.^18}{e[1]:}'
>>>s.format(i = i, e = e)
'GPB......0.8639......0.8399'
>>>
or
>>>i = 'GPB'>>>e = (0.8639, 0.8399)>>>s1 = '{{i:}}{{e[0]:.^{n:}}}{{e[1]:}}'>>>n = len(str(e[0])) + 12>>>s = s1.format(n=n)>>>s
'{i:}{e[0]:.^18}{e[1]:}'
>>>s.format(i = i, e = e)
'GPB......0.8639......0.8399'
>>>
Post a Comment for "Aligning With String Formatting"