'generating' a print statement

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu May 8 04:10:37 EDT 2003


"David Broadwell" <anti-spam.dbroadwell at mindspring.com> wrote in
news:qplua.7846$WA3.6988 at nwrddc03.gnilink.net: 

> I'm trying to avoid using a 'kluge' construct like;
> for item in range(len(temp)):
>     if  len(temp) == 5:
>         print "%s   %s  %s  %s  %s" %
> (temp[0],temp[1],temp[2],temp[3],temp[4])
>     elif len(temp) == 4:
>         print "%s   %s  %s  %s" % ((temp[0],temp[1],temp[2],temp[3])
>     elif len(temp) == 3:
>         print "%s   %s  %s" % (temp[0],temp[1],temp[2])
>     elif len(temp) == 2:
>         print "%s   %s" % (temp[0],temp[1])
>     elif len(temp) == 1:
>         print "%s" % (temp[0])
> 

Take this in two steps. temp is a sequence, and you want to pass all
members of that sequence in a tuple as the right hand argument of the
format operator. That's easy: 

     format % tuple(temp)

The left hand format string seems to be asking for %s formatting for
each argument with two spaces separating each %s. Instead of a for loop,
try using multiplication to repeat the string: 

either:

    format = "  ".join(['%s'] * len(temp))    

or:

    format = ("%s  " * len(temp)).rstrip()

Putting those together:
>>> temp = [1, 2, 3]
>>> format = "  ".join(['%s'] * len(temp))
>>> format % tuple(temp)
'1  2  3'


-- 
Duncan Booth                                            
duncan at rcp.co.uk int month(char
*p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3" 
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure? 




More information about the Python-list mailing list