Q:

Using .format() to center things that aren't substitutions

I'm using python to print out the contents of a list line by line with this:
header = ['State', 'AVG Loan Size', 'AVG Interest Rate', 'AVG Loan Duration']
widths = [ len(col) for col in header ]
print '{}\t{}\t{}\t{}'.format(*(header + widths))
for line in output:
    print '{0:^{4}}\t{1:^{5},.0f}\t{2:^{6},.1f}\t{3:^{7},.0f}'.format(*(line + widths))

Which gives me this:
State   AVG Loan Size   AVG Interest Rate   AVG Loan Duration
 CA        10,651             12.1                 41        
 TX        10,692             12.1                 42        
 VA        10,693             12.1                 42        
 GA        10,675             12.1                 42 

I now want to put a dollar sign at the beginning of the second column and " months" at the end of the last column. How can I achieve this? I need to define the width and centering for not just a substitution, but a substitution concatenated with literal characters.
For example, this code doesn't work:
print '{0:^{4}}\t${1:^{5},.0f}\t{2:^{6},.1f}\t{3:^{7},.0f} months'.format(*(line + widths))

resulting in this (note how the '$' and 'months' aren't included in the centering:
State   AVG Loan Size   AVG Interest Rate   AVG Loan Duration
 CA     $   10,651            12.1                 41         months
 TX     $   10,692            12.1                 42         months
 VA     $   10,693            12.1                 42         months
 GA     $   10,675            12.1                 42         months

A:

I can't be sure without seeing the origin of the line and width variables, but it appears that the table elements are being inserted into the string with the padding, and then you're adding the $ and "months". Try including the $ and "months" within the original table elements that you are inserting with format. In other words, leave your print statement as you had it originally in your first suggestion, and then make your changes instead on the line / width variables.  

