askvity

How can you print without a newline in Python?

Published in Python Printing 2 mins read

You can print without a newline in Python by using the end parameter in the print() function, or by using the asterisk (*) operator to unpack a list or tuple.

Using the end Parameter

The most common and straightforward method is to use the end parameter within the print() function. By default, end is set to \n (newline character), causing each print() statement to output on a new line. You can change this to any string, including an empty string "", to prevent the newline.

print("Hello", end="")
print("World")  # Output: HelloWorld

In this example, the first print() statement outputs "Hello" without a newline. The second print() statement then outputs "World" immediately after, resulting in "HelloWorld" on a single line. You can also use other characters or strings as the end parameter:

print("Hello", end=" ")
print("World")  # Output: Hello World

Here, a space is used as the end parameter, inserting a space between "Hello" and "World".

Using the Asterisk (*) Operator

The asterisk (*) operator can unpack a list or tuple, printing elements without newlines, but this method is less common for simple cases. This is particularly useful when you have a collection of items you want to print on the same line.

my_list = ["Hello", "World", "!"]
print(*my_list)  # Output: Hello World ! (separated by spaces)

By default, the * operator unpacks the list and separates the elements with spaces. You can control the separator using the sep parameter in the print() function:

my_list = ["Hello", "World", "!"]
print(*my_list, sep="")  # Output: HelloWorld!

Setting sep="" removes the spaces between the elements.

Summary

In summary, the end parameter within the print() function provides the most direct and flexible way to print without a newline in Python. The * operator offers an alternative approach, especially useful when dealing with collections of items.

Related Articles