Aligning Floats to decimal points in Python 2.7 using the format() mini-language

format, python, python-2.7

Solution

Use `' '` as the sign modifier to include a space for the sign:

>>> '{:20} {: }'.format('ydisp', 0.176)
'ydisp                 0.176'
>>> '{:20} {: }'.format('xdisp', -0.509)
'xdisp                -0.509'

Note the space after the `:` colon. This causes positive numbers to be padded with a space on the left, negative numbers display a `-` instead.

Problem

I want to print lines so that the decimal points of the numbers align. Currently, it prints like shown below: ``` ydisp 0.176 xdisp -0.509 ``` and what I want is something like this ``` ydisp 0.176 xdisp -0.509 ``` The code that I am using is ``` print "{:{width}} {}".format(items,float_dict[items], width=12) ``` but I am a little bit lost now, I found the following section in the Python 2.7 manual under the format Mini Language "Preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types. This is equivalent to a fill character of '0' with an alignment type of '='." I cannot really get it to work with this '0' character. It would be nice if someone could give me a hint here. Note: the dictionary keys are type string, and the values are type float.

Original source