Python: avoid new line with print command [duplicate]
Asked Answered
M

5

148

When I use the print command, it prints whatever I want and then goes to a different line. For example:

print "this should be"; print "on the same line"

Should return:

this should be on the same line

but instead returns:

this should be
on the same line

More precisely I was trying to create a program with if that told me whether a number was a 2 or not

def test2(x):
    if x == 2:
        print "Yeah bro, that's tottaly a two"
    else:
        print "Nope, that is not a two. That is a (x)"

But it doesn't recognise the last (x) as the value entered, and rather prints exactly: "(x)" (the letter with the brackets). To make it work I have to write:

print "Nope, that is not a two. That is a"; print (x)

And if e.g. I enter test2(3) that gives:

Nope, that is not a two, that is a
3

So either I need to make Python recognise my (x) inside a print line as the number; or to print two separate things but on the same line.

IMPORTANT NOTE: I am using version 2.5.4

Another note: If I put print "Thing" , print "Thing2" it says "Syntax error" on the 2nd print.

Minimus answered 29/6, 2012 at 17:9 Comment(2)
Add a comma (,) at the end of the line. Note that it will still make the print statement print a whitespace instead of a newline.Melchizedek
Answers arent the same, and most use the sys.stdout.write command (and it is a more advanced thread). Since i have started programming today, i did not understand them. (I found several more very similar threads, like 5, but i didnt understand or the questions werent the exact same)Minimus
S
198

In Python 3.x, you can use the end argument to the print() function to prevent a newline character from being printed:

print("Nope, that is not a two. That is a", end="")

In Python 2.x, you can use a trailing comma:

print "this should be",
print "on the same line"

You don't need this to simply print a variable, though:

print "Nope, that is not a two. That is a", x

Note that the trailing comma still results in a space being printed at the end of the line, i.e. it's equivalent to using end=" " in Python 3. To suppress the space character as well, you can either use

from __future__ import print_function

to get access to the Python 3 print function or use sys.stdout.write().

Staphyloplasty answered 29/6, 2012 at 17:10 Comment(7)
Will this work on Python 3? I'm asking, because print will require parens, and with parens and 2.7, this won't work.Grantor
@Grantor it won't work on 3.x, you suppress using print('whateverhere', end='') where end normally defaults to '\n'Corelation
@Jon Clements Thanks. I have not used Python 3, but saw somewhere about some of the changes between 2.x.Grantor
@Grantor You can try it yourself with (I think) 2.6+ (might be 2.7 though - that got most of the back-ports) with a from __future__ import print_function - just expect a lot of code to break :)Corelation
@Grantor Here's the link to the v3 print function docs, my answer below also shows some examples. PEP 3105 has also more info in the print function.Lawsuit
you don't want a whitespace in there for clarity? i.e. print("Nope, that is not a two. That is a ", x)Kolo
@Kolo print implicitly adds a space between each of its arguments. If you add one yourself, two spaces will be printed. In Python 3, you can use the sep keyword argument to control this behaviour.Staphyloplasty
L
125

In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.

import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

yields:

hi thereBob here.

Note that there is no newline or blank space between the two strings.

In Python 3.x, with its print() function, you can just say

print('this is a string', end="")
print(' and this is on the same line')

and get:

this is a string and this is on the same line

There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)

E.g.,

Python 2.x

print 'hi', 'there'

gives

hi there

Python 3.x

print('hi', 'there', sep='')

gives

hithere
Lawsuit answered 29/6, 2012 at 17:18 Comment(4)
sys.stdout.write works oddly. I don't know the syintax for it, could you give me an example of a simple sys.stdout.write command and its output?Minimus
import sys sys.stdout.write('hi there') sys.stdout.write('Bob here.') I copypaste that into my python and it gives absolutely no output when i press enter. Can this only be used inside a def function() or something?Minimus
@Minimus try adding this sys.stdout.flush() .. perhaps your IO doesn't get flushed.Lawsuit
Working now, I needed to put first: import sys (press enter)and then the write.stdout.sys stuff. Thanks a lot!Minimus
B
24

If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try

from __future__ import print_function

print("abcd", end='')
print("efg")

results in

abcdefg

For those using 3.x, this is already built-in.

Burseraceous answered 29/6, 2012 at 17:18 Comment(1)
Excellent! This is very useful for writing code that is compatible with both versions and will give the same results under both python 2 and python 3!Newsletter
C
13

You simply need to do:

print 'lakjdfljsdf', # trailing comma

However in:

print 'lkajdlfjasd', 'ljkadfljasf'

There is implicit whitespace (ie ' ').

You also have the option of:

import sys
sys.stdout.write('some data here without a new line')
Corelation answered 29/6, 2012 at 17:16 Comment(4)
The import sys; sys.stdout.write method has the advantage of working unchanged on Python 2.x and Python 3.x.Axes
import sys sys.stdout.write('some data here without a new line') this gives no output at all, I don't understand sys.stdout.write...Minimus
@Minimus because you have to sys.stdout.flush() after. sys.stdout is a buffered stream... It just so happens the print statement calls a flush implicitly.Corelation
In an attempt to make it clearer some_file_like_object.write() writes to the buffer. The buffer is only written when full or flushed or closed. stdin and stdout are buffered but stderr is not. print is basically sys.stdout.write('lkjsflajfsd\n').Corelation
E
5

Utilize a trailing comma to prevent a new line from being presented:

print "this should be"; print "on the same line"

Should be:

print "this should be", "on the same line"

In addition, you can just attach the variable being passed to the end of the desired string by:

print "Nope, that is not a two. That is a", x

You can also use:

print "Nope, that is not a two. That is a %d" % x #assuming x is always an int

You can access additional documentation regarding string formatting utilizing the % operator (modulo).

Eady answered 29/6, 2012 at 17:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.