Using print instead of file.write(str)

Alex Martelli aleax at mac.com
Sat Jun 3 20:03:01 EDT 2006


Tim Roberts <timr at probo.com> wrote:

> Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> wrote:
> 
> >Sion Arrowsmith a écrit :
> >> A.M <alanalan at newsgroup.nospam> wrote:
> >> 
> >>>I found print much more flexible that write method.
> >> 
> >> "more flexible"? More convenient, yes. More powerful, maybe. But I
> >> don't see more flexible. Everything print can to stdout.write() can
> >> do. The reverse isn't true. eg (this appears to be a FAQ on this
> >> group, although I can't find it in the FAQ):
> >> 
> >> for x in range(10):
> >>     sys.stdout.write(str(x))
> >> 
> >> to print:
> >> 
> >> 0123456789
> >
> >The reverse isn't true ???
> >
> >   print "".join(str(x) for x in range(10))
> 
> What he meant it that it is impossible to produce "0123456789" using 10
> separate print statements, while it IS possible with 10 separate writes.

it's not quite impossible, just cumbersome:

>>> for x in range(10):
...   print x,
...   sys.stdout.softspace=0
... 
0123456789>>> 

Yes, you do need the softspace assignments -- but then, in the write
version you need the explicit str calls, so it's not as if in either
case you're using "just" the print or write-call.

The differences in terms of convenience are surely there (in different
circumstances they will favor one or the other of the two approaches),
but I don't see such differences in either flexibility or power (if one
ignores the issue of convenience, the same tasks can be performed with
either approach).


Alex



More information about the Python-list mailing list