Separator in print statement

Bengt Richter bokr at oz.net
Thu Oct 16 07:00:06 EDT 2003


On Tue, 14 Oct 2003 12:32:34 -0400, Peter Hansen <peter at engcorp.com> wrote:

>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.

Maybe something familiar? ;-)

    import sys
    def printf(fmt, *args): sys.stdout.write(fmt%args)

or
    def sprintf(fmt, *args): return fmt%args # ok, a little different ;-)


>
>> '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

Regards,
Bengt Richter




More information about the Python-list mailing list