Using print with format to stdout generates unwanted space

Paul Watson pwatson at redlinepy.com
Mon Jun 20 17:36:09 CEST 2005


Thanks for all replies.

Ok.  I agree.  While printf() does tightly control formatting in C, it does 
not in Python.  Using write() can be used to output with no changes to the 
data.

"Tim Hoffman" <timh at zute.net> wrote in message 
news:42b6bc99 at news.highway1.com.au...
> Hi Paul
>
> Based on your description of what you want to do, print is probably  not 
> the correct method of controlling output format. You should use write() 
> method of the file handle to get unadulterated output.
>
> print is working as documented .  From the Python 2.3 documentation, 
> Section 6.6 The Print statement.
>
> "print evaluates each expression in turn and writes the resulting object 
> to standard output (see below). If an object is not a string, it is first 
> converted to a string using the rules for string conversions. The 
> (resulting or original) string is then written. 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."
>
> As you can see a space char is written and is correct as per the docs.
>
> Rgds
>
> Tim
>
> Paul Watson wrote:
>> #!/usr/bin/env python
>>
>> #   Using a print statement to stdout results in an
>> #   unwanted space character being generated at the
>> #   end of each print output.  Same results on
>> #   DOS/Windows and AIX.
>> #
>> #   I need precise control over the bytes that are
>> #   produced.  Why is print doing this?
>> #
>> import sys
>>
>> #   If this is a DOS/Windows platform, then put stdout
>> #   into binary mode so that only the UNIX compatible newline
>> #   will be generated.
>> #
>> try:
>>     import msvcrt, os
>>     msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
>> except:
>>     print 'This is not an msvcrt platform.'
>>     pass
>>
>> #   Using print with newline suppressed generates a space at the
>> #   end of each print statement.
>> #
>> for i in range(3):
>>     print '%d,60,' % (i),
>>     for j in range(10):
>>         print '%d,' % (j),
>>     print ''
>>
>> #   Using a list and doing a join does not result in the space
>> #   character being generated.
>> #
>> for i in range(3):
>>     alist = []
>>     alist.append('%d,60,' % (i))
>>     for j in range(10):
>>         alist.append('%d,' % (j))
>>     print ''.join(alist)
>>
>> sys.exit(0) 





More information about the Python-list mailing list