'generating' a print statement

Alex Martelli aleax at aleax.it
Thu May 8 07:01:33 EDT 2003


Duncan Booth wrote:
   ...
> 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'

If these specs are indeed correct, another alternative way to implement
them is to forego the % operator in favour of a direct application of
str to all items, followed by a join of the resulting strings:

'  '.join(map(str, temp))

should be equivalent to the two statements that build and then use the
format string, and it may be considered a bit clearer and more concise.


Alex





More information about the Python-list mailing list