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
  • 41,341
  • 63
  • 198
  • 344
  • "But I do not know how to do that." The documentation is not telling you how to avoid the problem you are asking about. The documentation is telling you how to make use of the behaviour you don't want, in other situations. – Karl Knechtel Jan 02 '23 at 00:36

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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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
  • 211,518
  • 52
  • 313
  • 390
  • 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