AppDividend
Latest Code Tutorials

Python Print No Newline: Print Without Newline in Python

0

The print() function in Python ends with a newline by default. Python has a predefined format. If you use print(var), then it will go to the next line automatically because the print() function will add a \n or space.

print("It is hard to get")
print("PS5 in India")

Output

It is hard to get
PS5 in India

Sometimes, you don’t want to go to the next line but print on the same line. Let’s see how to print multiple statements in the same line and not to print in the new line.

Python Print No Newline

To not add a new line to the end of the string in Python 3, use the end= parameter in the print() function. To print no new line in Python, use the end = “” argument in the print() function.

print('.', end='')

See the following example of print no line in Python.

print("It is hard to get", end=" ")
print("PS5 in India")

Output

It is hard to get PS5 in India

You can see that it prints on the same line rather than a different line.

Let’s take a list and iterate its elements using the for loop and print the numbers on the same line using the print(end = ” ) function.

list = [11, 21, 19, 46, 18]

for i in range(5):
    print(list[i], end=" ")

Output

11 21 19 46 18

Passing separator as an argument

To not add a space between all the function arguments, use the following code snippet.

print('x', 'y', 'z', sep='')

Output

xyz

You can pass any string to either parameter, and you can use both parameters simultaneously.

print('x', 'y', 'z', sep='*', end=" ")
print('a', 'b', 'c')

Output

x*y*z a b c

Passing a flush argument to the print() function

If you are facing trouble with buffering, use the flush argument in the print () function.

print('x', 'y', 'z', sep='*', end=" ", flush=True)

print('a', 'b', 'c')

Output

x*y*z a b c

Printing with no newlines in Python 2

To not add a new line to the end of the string in Python 2, use the comma at the end of your print() statement.

print "Sony is not counting",
print "India as Playstation market"

Output

Sony is not counting India as Playstation market

To print without space or newline, use the sys.stdout.write() functionTo work with the sys module, you need to import it first.

import sys

sys.stdout.write("Sony India is ")
sys.stdout.write("Worst division in Sony")

Output

Sony India is Worst division in Sony

Using functools.partial() function

The functools module in Python is used for higher-order functions. Use its partial() function to print the statements within the same line.

import functools

printf = functools.partial(print, end="")

printf("Dante's ")
printf("Inferno")

Output

Dante's Inferno

That is it for Print Without Newline in Python tutorial.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.