Excerpt from an email Danny Yoo sent to me and the list in 2005. I had the same question. ;-)
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! On 9/25/07, Tim <[EMAIL PROTECTED]> wrote: > > Hello, > I have a print statement where I use concatenation of variables with "+" > to > avoid extra whitespaces. The variables are mixed (float/int). > > How can I convert them all to strings to have a clean print statement? > > example > print str(var1)+"and this "+str(var2)+"needs to check "+str(var3) > > how can I convert var1, var2, var3 all at once? > > This would avoid errors because of mixed data types. > > BTW, why does a statment like > print var1, var2 > automatically add spaces between the variables? > > Thanks in advance for your help. > > Timmie > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor >
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor