Print text in Python without a new line
This post will discuss how to print a text without a newline in Python.
1. Using print() function
The built-in function print() is widely used in Python 3.x to print objects to the text stream. Consider the following code example, which demonstrates a simple usage of the print() function:
|
1 2 3 4 5 |
if __name__ == '__main__': print('Hello') print('World') |
The above code will print the string Hello and World in two different lines. This is because the print() function has an optional end argument, which defaults to a newline (\n). To avoid newline at the end, you can assign end to an empty string, as shown below:
|
1 2 3 4 5 |
if __name__ == '__main__': print('Hello', end='') print('World', end='') |
2. Using print statement
In Python 2, the print functionality has a statement dedicated to it. To interpret print(), you need to specify the from __future__ import print_function compiler directive. The following code demonstrates this usage of the print statement.
|
1 2 3 4 5 6 7 |
from __future__ import print_function if __name__ == '__main__': print('Hello', end='') print('World', end='') |
3. Using sys.stdout.write() function
Alternatively, you can use stdout for the output of print(). To write text to stdout, use sys.stdout.write() function.
|
1 2 3 4 5 6 7 |
import sys if __name__ == '__main__': sys.stdout.write('Hello') sys.stdout.write('World') |
That’s all about printing text in Python without a new line.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)