6

I have 2 separate print statements:

print "123"

print "456"

How can i make these 2 print statement appear on the same line? Note i need to use 2 print statements

output:

123456

Mike Daniels
  • 8,582
  • 2
  • 31
  • 44
hssss
  • 141
  • 1
  • 2

5 Answers5

7

In python 1.x and 2.x, a trailing comma will do what you want (with the caveat mentioned by others about the extra space inserted):

print "123",
print "456"

In python 3.x — or in python 2.6-2.7 with from __future__ import print_functionprint is a function and you should use end="" to force no extra ending character:

print("123", end="")
print("456")
Andrew Jaffe
  • 26,554
  • 4
  • 50
  • 59
  • Python 1.x? Seriously? I don't think there are any installations of this left (and even if, they should be nuked from the orbit). –  Dec 08 '10 at 18:40
  • @delnan: Yes there are and yes they should be. – martineau Dec 08 '10 at 19:51
6

A comma after the string you are printing will suppress the newline. The \b is a special character that represents an ASCII backspace.

print '123',
print '\b456'
Brent Newey
  • 4,479
  • 3
  • 29
  • 33
5
print "123",
print "456"

Alternatively, you can use sys.stdout.write:

sys.stdout.write('123')
sys.stdout.write('456\n')
nmichaels
  • 49,466
  • 12
  • 107
  • 135
4
print '123',
print '\b456'
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0
print "123",
print "456"

For Python 3+

print("123", end="")
print("456")
Kumar Sambhav Pandey
  • 1,713
  • 4
  • 22
  • 33