[Tutor] Where did those spaces come from?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Sep 13 03:55:39 CEST 2005



On Mon, 12 Sep 2005, Tom Tucker wrote:

> Good evening! The goal is to parse a simple file and grab column one.
> Then print each value horizontally separated by a comma.  Why is Python
> adding a space padding between each value? Please see below.  Thanks
> ahead of time.

Hi Tom,

The 'print' statement is hardcoded to add a space between elements.
print is meant to make output easy, at the cost of control.


If we need more fine-grained control over output, we may want to take a
look at the sys.stdout object; it's a file object that corresponds to the
output we send to the user.

#######
>>> import sys
>>> sys.stdout
<open file '<stdout>', mode 'w' at 0x2a060>
#######

As a file object, we can use the methods that files provide:

    http://www.python.org/doc/lib/bltin-file-objects.html

But the one we'll probably want is 'write()': the write() method of a file
object lets us send content out, without any adulteration:

######
>>> import sys
>>> for i in range(5):
...     sys.stdout.write('hello' + str(i))
...
hello0hello1hello2hello3hello4
######


We might have to be a little bit more careful with write(), because unlike
the print statement, the write() method isn't magical, and won't
automatically try to coerse objects to strings.  The code above shows that
we str() each number, and for good reason.  If we try without it, we'll
get a TypeError:

######
>>> sys.stdout.write(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: argument 1 must be string or read-only character buffer, not
int
######

So it just means we'll have to be more aware about the type of a value
when we use write().


For some more information, see:

    http://www.python.org/doc/tut/node9.html#SECTION009200000000000000000
    http://www.python.org/doc/tut/node9.html#SECTION009100000000000000000


Please feel free to ask more questions.  Good luck!



More information about the Tutor mailing list