2

I've written this program in Python 3 that takes a CSV file that finds the min and max death rates for particular states.

I've basically finished the program and it outputs correctly in the shell, but I have a problem:

  1. Different states have different lengths of characters in their names and the spacing does come out correctly, how do I use string formatting to make the strings space evenly regardless of the number of characters printed?

Here is what I have:

print ("\n", "Indicator                       |", "Min                   ",
       "        | Max     ")
print ("-----------------------------------------------------------------------------------------------")

This is the output:

enter image description here

It works well for "Minnesota" but for "District of Columbia" it doesn't format evenly.

Any suggestions? Thanks.

Goose
  • 2,130
  • 10
  • 32
  • 43

1 Answers1

5

Use string formatting as described here: http://docs.python.org/release/3.1.5/library/string.html

e.g.:

print('{:20} | {:20} {:5.2f} | {:20} {:5.2f}'.format(title, states[statemin], minimum, states[statemax], maximum))

Replace 20 with the longest string that will ever occur.

Note that I am assuming that minimum and maximum are floats, if they are strings, you cannot use '{:x.yf}' notation and you could just use {:6} or something like that instead.

{:20} means that 20 characters of space is used for the string, even if it is shorter (it does not truncate when longer). {:5.2f} means that 5 spaces are used for the float, of which 2 are after the decimal point.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
John Peters
  • 1,177
  • 14
  • 24