0

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.

blueFast
  • 37,437
  • 54
  • 182
  • 318

2 Answers2

4

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("BBBB\n")
    
  • Use the forward-compatible new print() function:

    from __future__ import print_function
    
    print("AAAA", end='')
    print("BBBB")
    
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
  • Thanks! All three are bad options for me :) but I guess there is no good option. I expected some flag for the `print` statement (similar to the final `,`), but I see there is no way of telling print "do not put a space". – blueFast Jan 25 '13 at 12:06
  • @gonvaled: That's one of the reasons Python 3 switched to a `print()` function; allowing you to actually alter the defaults. The `from __future__` import was added to help the transition from 2 to 3. – Martijn Pieters Jan 25 '13 at 12:11
2

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

from __future__ import print_function

print('foo', end='')
print('bar')
georg
  • 204,715
  • 48
  • 286
  • 369
  • This does mean that any module importing that for this case would require all `print` statements to be amended though – Jon Clements Jan 25 '13 at 11:14