Using print with format to stdout generates unwanted space

John Roth newsgroups at jhrothjr.com
Mon Jun 20 00:09:33 EDT 2005


Don't use print, write directly to sys.stdout.
Print is not intended for precise output formatting;
it's intended for quick outputs that are useable
most of the time.

John Roth


"Paul Watson" <pwatson at redlinepy.com> wrote in message 
news:3hmt4rFhnn89U1 at individual.net...
> #!/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