Print Without Newline in Python Programming With Examples

In different programming languages such as C, C++, Java, etc. by default, the printing statements do not end with a newline.

While in the case of Python, we see that the ‘print()’ function by default takes the cursor to the next line after printing the content in it. Let us look at an example where we try to print two different statements.

Output:

This could be useful while printing the content of each ‘print()’ statement in a newline. But sometimes the user may need to print stuff in the same line.

This could be achieved by using any of the two methods mentioned below for Python 2.0+ or Python 3.0+ users.

Printing with no newlines in Python 3.0+

In Python 3.0+ the ‘print()’ function comes with an additional optional argument ‘end’ which is actually nothing but the terminating string.

Taking the same example as above, but this time using the ‘end’ argument let’s see if we can print both the statements in a single line.

Output:

So we can clearly see that just by giving any string into the print function as ‘end’ (as an argument) we can actually separate the print statements with them.

For printing a list without Newline

We can similarly print the contents of a list or an Array without newlines as well. Let’s see how

Output:

Printing with no newlines in Python 2.0+

For Python 2, we can solve the above-mentioned problem by any of the two methods. Firstly if we wan to separate the print statement contents with space( ” ” ) we can use the ‘,’ operator.

Whereas, for other separating string we can use the sys.stdout.write a function from the Sys module in Python 2.

Again, for example, using ‘,’ operator,

Output:

Using sys.stdout.write function in place of ‘print()’,

Output:

For printing a list without Newline

Using ‘,’ operator

Again looking at an example,

Output:

Using the sys module function

Look at this example carefully,

Output:

For learning more about the print function in Python, refer to this article from JounalDev https://www.journaldev.com/15182/python-print

References:

https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space

https://legacy.python.org/search/hypermail/python-1992/0115.html

By admin

Leave a Reply

%d bloggers like this: