[Tutor] Re: [newbie] output formatting

Andrei project5 at redrival.net
Wed Nov 5 09:54:22 EST 2003

Eur van Andel wrote on Wed, 05 Nov 2003 14:26:05 +0100:

> Now I would like the 9.8 printed either as 09.8 or with an extra leading space.

Well, you're using the wrong numbers in your formatting:

>>> "%0.2f" % 3.14
'3.14' # no padding, 2 decimals
>>> "%02.2f" % 3.14
'3.14' # no padding, since the string is longer than 2 chars
>>> "%05.2f
'03.14' # padded with 0 up to 5 chars
>>> "%5.2f" % 3.14
' 3.14' # padded with spaces, total length = 5
>>> "%010.2f" % 3.14
'0000003.14'# padded with 0, total length = 10
>>> "%010.3f" % 3.14
'000003.140' # 10 long, 3 decimals, 0-padded

It's like this: "%xy.zf"

x can be either 0 (the string will be 0-padded if necessary), or absent
(padded with spaces if necessary). y determines the minimum total length of
the resulting string (including decimals and the dot). z determines the
number of decimals after the dot.

> Life is hard for Python newbies :-(

It's probably covered in more detail in one of the tutorials.

> PS. I'm used to:
>>for i = 1 to 10 do

> is it really true that I should do
>>for i in range(1,10+1)

Depends on your needs. If you just want to do something ten times, you'd
probably say:

for i in range(10):

and be done with it. If necessary, you could add 1 to i inside the string
if you need which loop this is. But generally speaking, it's wiser to count
from 0 than from 1, otherwise you'll run into trouble when accessing lists,
strings, and the likes because you'll need to keep converting back and



Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V
ernq gur yvfg, fb gurer'f ab arrq gb PP.

More information about the Tutor mailing list