Fanning Software Consulting

Left-Justify Column Output

QUESTION: I am trying to write an ASCII text file in which my output is in two columns of defined size. I have no trouble doing this in IDL, , using a format statement, but my output is always right-justified with respect to the column width. I would actually like one or both columns to be left-justified. Is there an easy way to do that in IDL?

ANSWER: Yes. Consider the code below, which writes two columns of data.

    OpenW, 1, 'example.txt'
   PrintF, 1, 'Favorite Animal:', 'coyote', FORMAT='(A25, x, A20)'
   PrintF, 1, 'Lucky Number:', 7, FORMAT='(A25, x, I20)'
   PrintF, 1, 'Most Useful Constant:', 3.14159, FORMAT='(A25, x, F20.5)'
   Close, 1 

This produces right-justified output, as shown below.

             Favorite Animal:               coyote
               Lucky Number:                    7
       Most Useful Constant:              3.14159 

However, if you put a minus sign ("-") in front of the number for the width, the data is left-justified instead of right-justified. Consider this code, which will left-justify the right-side column.

    OpenW, 1, 'example.txt'
   PrintF, 1, 'Favorite Animal:', 'coyote', FORMAT='(A25, x, A-20)'
   PrintF, 1, 'Lucky Number:', 7, FORMAT='(A25, x, I-20)'
   PrintF, 1, 'Most Useful Constant:', 3.14159, FORMAT='(A25, x, F-20.5)'
   Close, 1 

The output looks like this.

            Favorite Animal: coyote              
               Lucky Number: 7                   
       Most Useful Constant: 3.14159              

You can also left justify both columns, like this.

   OpenW, 1, 'example.txt'
   PrintF, 1, 'Favorite Animal:', 'coyote', FORMAT='(A-25, x, A-20)'
   PrintF, 1, 'Lucky Number:', 7, FORMAT='(A-25, x, I-20)'
   PrintF, 1, 'Most Useful Constant:', 3.14159, FORMAT='(A-25, x, F-20.5)'
   Close, 1 

The output with both columns left-justified is shown below.

   Favorite Animal:          coyote              
   Lucky Number:             7                   
   Most Useful Constant:     3.14159              

Version of IDL used to prepare this article: IDL 7.0.3.

Google
 
Web Coyote's Guide to IDL Programming