anio anio - 5 months ago 25
Python Question

How do I make a fixed size formatted string in python?

I want to create a formatted string with fixed size with fixed position between fields. An example explains better, here there are clearly 3 distinct fields and the string is a fixed size:

XXX 123 98.00
YYYYY 3 1.00
ZZ 42 123.34

How can I apply such formatting to a string in python (2.7)?


Sure, use the .format method. E.g.,

print '{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98)
print '{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0)
print '{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34)

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.