detrail the trailing space in print statement

Alex Martelli aleaxit at yahoo.com
Sat Oct 21 19:02:20 EDT 2000


"June Kim" <junaftnoon at nospamplzyahoo.com> wrote in message
news:8st23s$lpa$1 at news.nuri.net...
> I'd searched the deja news archive for a couple of mins
> and I found out the right answer. For other newbies'
> information, I post it here.
>
> Use sys.stdout.write, which will output the raw string per se.
    [snip]
> > for i in (a list of a huge size):
> >     do something quite complex
> >     print f(i),
> >     do something else
    [snip]
> > In this code, what I really want to do is printing out "f(i)"
> > as a stream. I can remove the newline character by
> > adding a comma but cannot remove the trailing space
> > which is automatically inserted at the end of the object.

Actually, the print statement doesn't "automatically insert"
the trailing space at that time -- it just sets the .softspace
attribute on sys.stdout to 1.  The NEXT forthcoming print
will test that attribute and start with the space if needed.

In other words, you CAN 'remove the trailing space' while
using the print statement rather than the write function,
if you wish...:

    for i in hugelist:
        dofoobar(i)
        print f(i),
        sys.stdout.softspace=0
        dobarbaz(u)

Using sys.stdout.write(str(f(i))) may indeed be better, but
I did want to point out that print is subtler than one might
think... sometimes that can come in handy.


Alex






More information about the Python-list mailing list