Python: Print without newline

The objective of this tutorial is to learn how to print content in Python with the print function, without adding a new line at the end of the content. This tutorial was tested on version 3.7.2 of Python, using IDLE.

The print function is one of the most basic built in functions of Python and it allows us to print content. We simply need to call the function and pass as argument what we want to print.

Nonetheless, one particularity of this function is that, every time we call it without providing any additional argument, it will add a newline at the end of the content.

So, if we invoke the print function twice like shown below, it will print the content in two different lines.

print("print 1")
print("print 2")

The result from running these two lines of code can be seen in figure 1.

Output of two print function calls in Python.
Figure 1 – Output of two print function calls.

This happens because the function receives as optional input a parameter called end that is appended to the content. As can be seen in the function definition, this optional parameter defaults to “/n” when not specified, which explains the behavior we saw.

So, if we don’t want a newline (or any other string) to be appended to the content, we simply need to specify the end argument to be equal to an empty string. You can check below the same prints as before, but now with this argument set to an empty string.

print("print 1", end='')
print("print 2", end='')

The result can be seen below in figure 2.

Output of two print function calls, with the end argument set to an empty string.
Figure 2 – Output of two print function calls, with the end argument set to an empty string.

Note that we can specify any string we want to be appended to the content we pass to the print function. We will also test it with a “/” character.

print("print 1", end='/')
print("print 2", end='/')

The result can be seen below in figure 3.

Output of two print function calls, with the end argument set to a "/" character
Figure 3Output of two print function calls, with the end argument set to a “/” character.

Leave a Reply

%d bloggers like this: