[Tutor] format command help

Alan Gauld alan.gauld at btinternet.com
Tue Oct 7 17:45:38 CEST 2014


On 07/10/14 14:40, Richard Dillon wrote:
> I create column headings using \t
>
>       print('base1\tbase2\theight\tarea')
>
> and I would like the numbers to align with the headings.
 > I think that I need to use format instead of doing this:

Yes, using tabs is a bit hit and miss depemding on the length of the 
fields. If they are all similar sizes its OK but otherwise it gets messy.

>      print(A,'     ',B,'     ',C,'     ',int(area1))
>      print(D,'     ',E,'     ',F,'     ',int(area2))
>
> but I don't know how.

At its simplest you just use braces like this:

fmtString = "{}\t{}\t{}\t{}"

print(fmtString.format('base1','base2',height','area'))

And that gives you your header line then

print(fmtString.format(A,B,C,int(area1))

gives you your first line and so on. By using a
constant fmtString you avoid any risk of mixing things up.

But formatting gives you more options. You can specify
width and justification. By using a fixed width you are
more likely to get the alignment consistent than by using
tabs. Here is an example:

fmtString="{:20}{:20}{:10}{:6}"

Then your prints stay the same but the formatting will
now use the fixed lengths you gave rather than rely
on tabs.

You can specify which end of the space you want the data
by using the < and > justification characters. So to pull
the integer to the left hand siode of its column use:

fmtString="{:20}{:20}{:10}{:<6}"

You can specify the type too but often you don't need
to since Python will do conversion to string for you.

There's lots more. Read the documentation on format
and play with different format strings in the interpreter.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list