Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I suppress the newline after a print statement?

I read that to suppress the newline after a print statement you can put a comma after the text. The example here looks like Python 2. How can it be done in Python 3?

For example:

for item in [1,2,3,4]:
    print(item, " ")

What needs to change so that it prints them on the same line?

like image 334
Ci3 Avatar asked Aug 24 '12 03:08

Ci3


People also ask

How do I stop the next line from printing in Python?

It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.

What is the use of \n in the print () function?

The Python print() function takes in python data such as ints and strings, and prints those values to standard out. To say that standard out is "text" here means a series of lines, where each line is a series of chars with a '\n' newline char marking the end of each line.

What character is used to print new line in a print if statement?

The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.


3 Answers

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
like image 88
Levon Avatar answered Oct 21 '22 13:10

Levon


Code for Python 3.6.1

print("This first text and " , end="")

print("second text will be on the same line")

print("Unlike this text which will be on a newline")

Output

>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
like image 22
Jasmohan Avatar answered Oct 21 '22 13:10

Jasmohan


print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:

print "Foo %10s bar" % baz,
like image 4
Miles F. Bintz II Avatar answered Oct 21 '22 14:10

Miles F. Bintz II