26

how can I output text to the console without new line at the end? for example:

print 'temp1'
print 'temp2'

output:

temp1 
temp2

And I need:

temp1temp2
jww
  • 97,681
  • 90
  • 411
  • 885
Max Frai
  • 61,946
  • 78
  • 197
  • 306

6 Answers6

37

Add a comma after the last argument:

print 'temp1',
print 'temp2'

Alternatively, Call sys.stdout.write:

import sys
sys.stdout.write("Some output")
adamb0mb
  • 1,401
  • 1
  • 12
  • 15
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
28

In Python > 2.6 and Python 3:

from __future__ import print_function

print('temp1', end='')
print('temp2', end='')
Olivier Verdier
  • 46,998
  • 29
  • 98
  • 90
6

Try this:

print 'temp1',
print 'temp2'
Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
4

There are multiple ways, but the usual choice is to use sys.stdout.write(), which -- unlike print -- prints exactly what you want. In Python 3.x (or in Python 2.6 with from __future__ import print_function) you can also use print(s, end='', sep=''), but at that point sys.stdout.write() is probably easier.

Another way would be to build a single string and print that:

>>> print "%s%s" % ('temp1', 'temp2')

But that obviously requires you to wait with writing until you know both strings, which is not always desirable, and it means having the entire string in memory (which, for big strings, may be an issue.)

Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
  • sys.stdout.write() also seems to append the number of characters to the output. sys.stdout.write("test") prints test4. Why is it doing this, and how do I make it stop? – Tom Aug 20 '16 at 00:21
0
for i in range(4): 

    print(a[i], end =" ") 
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Ankit
  • 1
  • While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run. – Lux Sep 09 '18 at 03:39
-1

Try

print 'temp1',
print '\btemp2'
Zulu
  • 8,765
  • 9
  • 49
  • 56