Separator in print statement
Peter Otten
__peter__ at web.de
Wed Oct 15 04:10:19 EDT 2003
Bertram Scharpf wrote:
> when I write
>
> >>> print 'abc', 'def',
> >>> print 'ghi'
>
> I get the output 'abc def ghi\n'.
>
> Is there a way to manipulate the print
> statment that I get for example:
>
> 'abc, def, ghi\n'
>
> I mean: can I substitute the ' ' separator produced from
> the comma operator by a e.g. ', ' or something else?
Unfortunately, the delimiter for print is currently hardcoded.
Here's some hackish code that will do what you want (most of the time).
<code>
import sys
class DelimStream(object):
def __init__(self, stream, delim):
self.stream = stream
self.delim = delim
self._softspace = False
def _set_softspace(self, b):
if b:
self._softspace = True
def _get_softspace(self):
return False
softspace = property(_get_softspace, _set_softspace)
def write(self, s):
if self._softspace:
if s != "\n":
self.stream.write(self.delim)
self._softspace = False
self.stream.write(s)
d = DelimStream(sys.stdout, ", ")
#works most of the time
print >> d, "foolish", "consistency", "hobgoblin", "little", "minds"
print >> d, "seen", "hell", "himmel", "weich"
#but not always:
print "A", "B", "\n", "C"
print >> d, "A", "B", "\n", "C" #note the missing delim before the C :-)
if 1: #not recommended
sys.stdout = DelimStream(sys.stdout, ", ")
print "foolish", "consistency", "hobgoblin", "little", "minds"
</code>
Peter
More information about the Python-list
mailing list