[Tutor] Re: How can I format rows of irregular sized strings to print in columns?

Bob Gailer bgailer at alum.rpi.edu
Fri May 7 09:21:44 EDT 2004

At 07:43 PM 5/6/2004, Bob Gailer wrote:
>At 04:31 PM 5/6/2004, Lee Harr wrote:
>>>I wrote a little program to look for graphics files and tell me the image
>>>size and the file size of each file. The data prints out like this:
>>>(292, 240) 35638 defender.bmp
>>>(1024, 768) 2359350 evolution3.bmp
>>>(78, 76) 17990 GRID1A.bmp
>>>How can I make it so that it looks more like this:
>>>( 292,  240)    35,638  defender.bmp
>>>(1024,  768) 2,359,350  evolution3.bmp
>>>(  78,   76)    17,990  GRID1A.bmp
>>Please post only in plain text.
>>You will want to look at the string formatting operator:
>>One handy example:
>>>>>a='(292, 240)';b=35638; c='defender.bmp'
>>>>>print '%10s %10s %20s' % (a, b, c)
>>(292, 240)      35638         defender.bmp
>This solution is close, but I think the OP wants the numbers in () to be 
>individually aligned in columns. The desired output in proportional font 
>doesn't show this, but if you copy/paste into a fixed font editor you will 
>see this more clearly.

OOPS. I have now done my "homework" and realize that im.size returns a 
tuple of numbers rather than a string. So we don't need re after all. The 
solution now is

     print '(%4s, %4s)' % imagesize, '%10s' % 
os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1]


And now for some code refinement:

while len(bmpfiles)>0:
     print '(%4s, %4s)' % imagesize, '%10s' % 
os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1]

Can be simplified using a for loop:

for bmpfile in bmpfiles:
     print '(%4s, %4s)' % imagesize, '%10s' % 
os.path.getsize(bmpfiles[-1]), '%12s' % bmpfiles[-1]

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625 home
720 938 2625 cell 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20040507/cd233b57/attachment.html

More information about the Tutor mailing list