[Tutor] Re: How can I format rows of irregular sized
strings to print in columns?
Bob Gailer
bgailer at alum.rpi.edu
Thu May 6 21:43:12 EDT 2004
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:
>http://docs.python.org/lib/typesseq-strings.html
>
>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.
So the challenge is to parse the numbers out and format them individually.
I think this is best done using re:
import re
m = re.match(r'\((\d+),\s*(\d+)\)', im.size) # generates a match object
with 2 groups
# m.groups() is ('292', '240')
'(%4s, %4s)' % m.groups() # is '( 292, 240)'
re can be daunting at first but is well worth the learning curve. So let''s
break the regular expression \((\d+),\s*(\d+)\) into pieces:
\( # match a left parentheses
\s* # match 0 or more "whitespace" characters
(\d+) # match one or more digits and place them in a group
, # match a comma
\s* # match 0 or more "whitespace" characters
(\d+) # match one or more digits and place them in another group
\) # match a right parenthesis
The result is placed in a "match object". m.groups() returns all the groups
in a tuple, which is the desired right argument type for %
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/20040506/cd6de66e/attachment.html
More information about the Tutor
mailing list