print and softspace in python

Phoe6 orsenthil at gmail.com
Wed Mar 14 12:12:56 EDT 2007


print and softspace in python
In python, whenever you use >>>print statement it will append a
newline by default. If you don't want newline to be appended, you got
use a comma at the end (>>>print 10,)
When, you have a list of characters and want them to be printed
together a string using a for loop, there was observation that no
matter what there was space coming between the characters. No split
or  join methods helped.
>>>list1=['a','b','c']
>>>for e in list1:
           print e,
a b c
>>># Without whitespace it will look like.
>>>print "abc"
abc

The language reference says that print is designed to output a space
before any object. And some search goes to find and that is controlled
by softspace attribute of sys.stdout.
Way to print without leading space is using sys.stdout.write()

>>>import sys
>>>for e in list1:
          sys.stdout.write(e)
abc

Reference manual says:
A space is written before each object is (converted and) written,
unless the output system believes it is positioned at the beginning of
a line. This is the case (1) when no characters have yet been written
to standard output, (2) when the last character written to standard
output is "\n", or (3) when the last write operation on standard
output was not a print statement. (In some cases it may be functional
to write an empty string to standard output for this reason.)

Question to c.l.p
Am Not getting the last part as how you will write  a empty string and
use print  not appending  blank space in a single line. Am not getting
the (In some cases... ) part of the reference manual section. Please
help.




More information about the Python-list mailing list