Python Print without Newline: If you have started your Python Programming journey, then you must faced a problem regarding print operation in Python.
Since, Python is among the top Programming Languages, so it becomes necessary to cover this topic as well.
Unlike traditional Programming Languages like – C, C++ or Java, In Python by default the Newline (\n) is automatically added to the end of print statement.
For example – In C++, when we write strings in cout statements. Then we get the output in same line.
cout << "Visit "; cout << "WWW.THECODERPEDIA.COM";
However, when we print statements using print() function in python, we get the output in 2 different lines.
So, In Python it automatically add “\n” after the end of the statement.
However, what if we want our statements in same line.
Like – Visit www.thecoderpedia.com
So, today we will be learning to print the statements in Python without Newline (\n).
Print without Newline in Python
Here are the top 3 methods you can use to perform print operation without newline in Python:
1. Printing without Newline using comma in Python 2
If you are using the Python 2 version, then you can very easily print a statement without newline. You just have to add comma(,) after the end of the print method.
So, as you can see that our output is now printed on the same line.
However, by using this method you will automatically get a space between two statements.
If you don’t want the space between two lines. Then you have to use the second method which we have discussed below.
2. By using sys module in Python 2
In Python 2, we also get another way to perform the same operation.
To use this method we have to import sys module.
Then instead of using print() method, we have to use sys.stdout.print() method.
import sys sys.stdout.print("Visit") sys.stdout.print("WWW.THECODERPEDIA.COM")
3. Printing without Newline using end in Python 3
As most of us are using the latest version of Python which is Python 3.
So, let’s take a look at the method by which you can remove the newline from the print() method in Python 3 version as well.
In this, you have to add the “end” argument after the first argument in the print() method.
print("Visit", end = "") print("WWW.THECODERPEDIA.COM")
However, if you want space in between the strings, then you can do so by adding space inside the end argument.
print("Visit", end = " ") print("WWW.THECODERPEDIA.COM")
So, these were the top 3 methods which you can use to perform print operation without newline.
Hope you like the article. If you have any suggestion or point which should be in this article, let us know in the comment section below.