How to print without newline in Python
In this article, we will see different methods to print without newline in Python. We will also learn about how to use those methods.
Different methods to print without newline in Python
- Using the ‘end’ parameter
- Using for loop
- Using sys.stdout.write()
1. Using the ‘end’ parameter
In this, we use the end parameter at the end of the string in the print statement.
print("Hello, ", end="") print("world!")
In the above code, after writing ‘Hello’, in the first print statement, we are mentioning end=” ”. The end parameter tells the program to print the next statement in the same line. The above code will print Hello and World words in the same line.
Output:
Hello, world!
2. Using for loop
for i in range(5): print(i, end=" ")
In the above code, we are using the end parameter but under for loop. It is particularly helpful when we want to print a series of statements in the same line. The above code will print numbers 0 to 4 in the same line as below.
Output:
0 1 2 3 4
import sys sys.stdout.write("Code") sys.stdout.write("Speedy")
In the above code, first, we import the sys module. Then using stdout.write() function we are writing the string to be displayed as output. stdout.write() telling the system not to write the new print statement to newline. Instead, write it in the same line.
Output:
The 6 in the output shows the number of characters in the second word,i.e. ‘Speedy’.
Note: Apart from this standard method, we can write our logic to print statements without newline. See the code below:
l = [str(i) for i in range(4)] print(' '.join(l))
In the above code, first, we create a list of numbers where each number we are creating a string using the str()
function. Then we use using .join()
method to join all the elements in the list and print it.
Output:
Similarly, you can define your logic to print without a newline.
Leave a Reply