Separator in print statement
Peter Hansen
peter at engcorp.com
Tue Oct 14 12:32:34 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:
The general rule with "print" is that it works like it does, and
if you don't like the way it works, you need to switch to something
else.
> 'abc, def, ghi\n'
>
> I mean: can I substitute the ' ' separator produced from
> the comma operator by a e.g. ', ' or something else?
If you require that the output be generated by separate statements
or subroutine calls, then you will have to do something fairly
complicated: create an object which acts like a file object, and
which can collect blobs of data as you output them, but hold
them in memory, writing them all out together after you send
it the terminating sequence (\n in this case).
A simpler option is just to collect up the bits of output that
you need in a list, then use the string join() method to generate
the output:
outList = []
outList.extend(['abc', 'def'])
outList.append('ghi')
print ', '.join(outList)
I've included both the .extend() and .append() approaches, to
most closely emulate your above example. You don't need to
use .extend() if you don't want, and the code might be simpler
if you don't.
-Peter
More information about the Python-list
mailing list