Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Python Print Without Newline

There are different ways through which we can print to the console without a newline. Let’s quickly go through some of these methods.


1. Using print()

We can use the print() function to achieve this, by setting the end (ending character) keyword argument appropriately.

By default, this is a newline character (\n). So, we must change this to avoid printing a newline at the end.

There are many options for this choice. We could use a space to print space-separated strings.

a = "Hello"
b = "from AskPython"

print(a, end=' ')
print(b)

This would print strings a and b, separated by a single space, instead of a newline.

Output

Hello from AskPython

We could also print them consecutively, without any gap, by using an empty string.

a = "Hello"
b = "from AskPython"

print(a, end='')
print(b)

Output

Hellofrom AskPython

2. Printing list elements without a Newline

Sometimes, when iterating through a list, we may need to print all its elements on the same line. To do that, we can again use the same logic as before, using the end keyword argument.

a = ["Hello", "how", "are", "you?"]

for i in a:
    print(i, end=" ")

Output

Hello how are you?

3. Using the sys module

We can also use the sys module to print without a newline.

More specifically, the sys.stdout.write() function enables us to write to the console without a newline.

import sys
sys.stdout.write("Hello from AskPython.")
sys.stdout.write("This is printed on the same line too!")

Output

Hello from AskPython.This is printed on the same line too!

4. Creating our own C style printf() function

We can also create our custom printf() function in Python! Yes, this is possible using the module functools, which allows us to define new functions from existing ones via functools.partial()!

Let’s use the same logic on the end keyword argument on print() and use it to create our printf() function!

import functools

# Create our printf function using
# print() invoked using the end=""
# keyword argument
printf = functools.partial(print, end="")

# Notice the semicolon too! This is very familiar for a
# lot of you!
printf("Hello!");
printf("This is also on the same line!");

Output

Hello!This is also on the same line!

We can also combine the semicolon to this (Python compiler will not complain) to bring back our C printf() function as it was!


References