[Tutor] high score lists

Chris Smith smichr at bigfoot.com
Sat Apr 16 05:47:34 CEST 2005


On Friday, Apr 15, 2005, at 18:46 America/Chicago, 
tutor-request at python.org wrote:

> I did look at your example about using the longest number, but I
> couldnt really understand all of the code, and ended up deciding to
> arrange it so that the two columns were left-aligned: it looked like
> it would align them down the center in your example? Let me know if I
> am misunderstanding something.
>
Those that are fluent in using the string formatting will groan, but I 
usually don't need fancy formatting and can get by with pretty simple 
commands. I just printed the first column right formatted and printed 
the name right next to it (so it appeared to be left formatted). The 
comma in the print statement added the space.

Here is my simple-minded way of thinking about the two column problem:
	
1) get the data into fixed width strings
2) add those two strings together and print them

Now, as you are seeing, the alignment options for a string will fill in 
the padding spaces that you need.  Figuring out how long each column 
should *minimally* be (based on the actual data) is an extra layer of 
difficulty, but to keep it simple you could just pick widths that you 
think are reasonable and then do something like this:

###
high = [(1000,"Denise"), (945,"Denise"), (883,"Denise"),
                  (823,"Grant"), (779,"Aaron"), (702,"Pete"),
                  (555,"Tom"), (443,"Tom"), (442,"Robin"), (404,"Pete")]

for score, who in high:
	col1 = str(score).rjust(10)
	col2 = who.rjust(20).replace(' ', '.') #replace spaces with dots
	print col1 + col2
###
--the output--
       1000..............Denise
        945..............Denise
        883..............Denise
        823...............Grant
        779...............Aaron
        702................Pete
        555.................Tom
        443.................Tom
        442...............Robin
        404................Pete
--end output--



More information about the Tutor mailing list