[Tutor] Formatter
Don Arnold
Don Arnold" <darnold02@sprynet.com
Sat Jan 18 23:08:01 2003
----- Original Message -----
From: "andy surany" <mongo57a@comcast.net>
To: "Pete Versteegen" <pversteegen@gcnetmail.net>; "Bob Gailer"
<ramrom@earthling.net>; <Tutor@python.org>
Sent: Saturday, January 18, 2003 8:06 PM
Subject: Re: [Tutor] Formatter
> I learned from this example as well.... Thanks!!
>
> I noticed that the format of each field is right justified. How would
> you make it left justified?
>
> Andy
This lets you prepend '-' to the specifier to left justify the field. I
swapped the format string and values arguments so you don't need to specify
the values in a tuple.I also flipped the function of the 'a' and 'x'
specifiers so they match the original specification:
def format(format, *values):
formatlist = format.split(',')
sf = ''
for formatitem in formatlist:
if formatitem[0] == '-':
leftjust = 1
formatitem = formatitem[1:]
else:
leftjust = 0
type = formatitem[0]
if type in 'fi':
sf += '%' + (leftjust * '-') + formatitem[1:] + type
if type == 'a':
sf += '%' + (leftjust * '-') + formatitem[1:] + 's'
elif formatitem[-1] == 'x':
sf += ' '*int(formatitem[:-1])
return sf % values
a = 5
alf = 'qwer'
i = 3
print '------------------------------------------------'
print format("f10.2,a10,10x,i5",a,alf,i)
print format("-f10.2,-a10,10x,-i5",a,alf,i)
print '12345678901234567890123456789012345 RULER LINE'
[script run (looks bad without a fixed-width font):]
------------------------------------------------
5.00 qwer 3
5.00 qwer 3
12345678901234567890123456789012345 RULER LINE
HTH,
Don
P.S. Big thanks to Bob! I never would've been able to come up with his
original code on my own.