> How do I output a string WITHOUT the trailing space when I do:
> print 'this string',
You can always format an output string manually:
out = `a`
for ...
if ...:
out = out + ','
print out + `b`
Better, why not just write a module or class to do it for you.
I've tacked on 2 trivial examples below:
writeln.py (module)
writeln2.py (class)
that simulate Pascal's write/writeln operations, and avoid
the extra space between items. The class is probaby better,
since you can create multiple streams, and a stream is
automatically flushed on exit (in the destructor). You can
also simulate C's printf() model (always use strings, and
check for '\n'), but it's less convenient.
Since you can redirect stdout to any object that implements
write() and flush() methods (thanks to Python's deep object
oriented nature), you could intercept print statement
text directly, with something like this:
import sys
class Output:
def __init__(self):
self.data = ''
def flush(self):
return None
def write(self, str):
# 'print' text comes here
<check for and strip inserted blanks in str>
self.data = self.data + str
class NoBlanks:
def __init__(self):
self.data = Output()
self.prior, sys.stdout = sys.stdout, self.data
def __del__(self):
sys.stdout = self.prior
print self.data.data # back to real stdout
x = NoBlanks()
print a,
for ....
print ',',
print b
x = [] # force destructor
But this won't work, since you can't distinguish between
blanks inserted by 'print', and ones you printed explicitly.
It would suffice, if you never plan to print a real blank.
Mark Lut
lutz@kapre.com
====================================================================
# MODULE WRITELN.PY
_line = []
def write(*objs):
for x in objs:
_line.append(x)
def writeln(*objs):
global _line
apply(write, objs)
str = ''
for x in _line:
if type(x) != type(''):
x = `x`
str = str + x
print str
_line = []
# USE ############################
# from writeln import *
# a = 111; b = 222
#
# write('<', a, '>')
# for x in range(1,4):
# if 1:
# write(',')
# writeln('<', b, '>')
#
# <111>,,,<222>
##################################
====================================================================
# MODULE WRITELN2.PY
class Output:
def __init__(self):
self.line = []
def __del__(self):
if self.line:
self.writeln()
def write(self, *objs):
for x in objs:
self.line.append(x)
def writeln(self, *objs):
apply(self.write, objs)
str = ''
for x in self.line:
if type(x) != type(''):
x = `x`
str = str + x
print str
self.line = []
# USE ############################
# from writeln2 import Output
# out = Output()
#
# out.write('<', a, '>')
# for ...
# if ...:
# out.write(',')
# out.writeln('<', b, '>')
##################################