82

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)?

anio
  • 8,903
  • 7
  • 35
  • 53

1 Answers1

177

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.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')
arrubo
  • 3
  • 3
Levon
  • 138,105
  • 33
  • 200
  • 191
  • 11
    Note: `7.2f` enforces the precision of 2, but 7 is just a _minimum_ width. For inputs that don't jive with formats, you may not get a width of 7. e.g. even though 12345.7 is only 7 characters, `'{:7.2f}'.format(12345.7)` has a width of 8. – jkmacc May 29 '14 at 18:44
  • @jkmacc good point, thanks for explicitly stating this (the link provides more information on this, and more, as well right at the top #4, but this is more explicit/easier:) – Levon May 29 '14 at 19:14
  • 3
    As a follow up to this question. How would you be able to introduce a variable "nchar", that specified the number of characters that the first string contains? For example, not to put in each line that you want 10 characters for the string, but to introduce in the format method a variable containing the number of desired characters in the first string? – antoine Jun 17 '15 at 10:31
  • 4
    @antoine If I understand your question correctly, you may want to take a look at this http://stackoverflow.com/questions/10875121/using-format-to-format-a-list-with-field-width-arguments -- hope that helps. – Levon Jun 17 '15 at 12:45