Puzzling input problem

Alex Martelli aleaxit at yahoo.com
Thu Mar 22 03:05:06 EST 2001


"Stephen R. Figgins" <fig at monitor.net> wrote in message
news:3AB97E58.7B01D485 at monitor.net...
> > Actually, raw_input isn't the culprit, exactly.  The print
> > statement's format handler doesn't know that raw_input() has
> > modified the screen contents, so it still behaves like the cursor is
> > just after the "prompt string: " on the screen, inserting a space
> > as the ref guide says it will.
>
> Hmmm... very interesting.  The first print doesn't put the space in
> right away, but waits for the next call to the print statement to add
> the space.  That is not what I would have expected.  Interesting!

Makes sense if you think of it -- if the next character to
be output is a newline, you probably don't want a trailing
space on the previous line.  To control this, the print
statement uses an attribute named 'softspace' on the file
(or file-like) object it's printing to (normally, the file
object referenced by sys.stdout, unless you're using a
'print>>bah' statement): when it's about to emit a space
that is 'soft' (that is, is present just because print
space-separates fields), rather than emitting it at once,
it sets the softspace attribute to one; when it's about to
emit to that file again, it checks the softspace attribute,
and, if 1, first emits a space, then resets softspace to 0.

This gives you a chance to retroactively 'cancel' the
soft space that would normally be emitted, by manually
resetting the softspace attribute to 0, although it's
not a frequent need -- still, it does work:

>>> print 'one',; sys.stdout.softspace=0; print 'two'
onetwo
>>>


Alex






More information about the Python-list mailing list