Avoid spurious space in print

Question:

I did not expect this, but:

print "AAAA",
print "BBBB"

Will output:

AAAA BBBB

With an extra space in the middle. This is actually documented.

How can I avoid that supurious space? The documentation says:

In some cases it may be functional to write an empty string to standard output for this reason.

But I do not know how to do that.

Asked By: blueFast

||

Answers:

Get used to use print() function instead of the statement. It’s more flexible.

from __future__ import print_function

print('foo', end='')
print('bar')
Answered By: georg

Three options:

  • Don’t use two print statements, but concatenate the values:

    print "AAAA" + "BBBB"
    
  • Use sys.stdout.write() to write your statements directly, not using the print statement

    import sys
    
    sys.stdout.write("AAAA")
    sys.stdout.write("BBBBn")
    
  • Use the forward-compatible new print() function:

    from __future__ import print_function
    
    print("AAAA", end='')
    print("BBBB")
    
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.