Python Printing Without New Line – Tutorial with Examples

In Python, by default, the print() function adds a new line after the output. However, sometimes you might want to print multiple values on the same line, or print without adding a new line after the output. This article will explain how to print without a new line in Python.

Method 1: Using the end parameter

The print() function has an optional parameter called end which allows you to specify the end character of the output. By default, the end character is a new line, but you can change it to any other character, including an empty string, which will prevent the new line from being added after the output.

print("Hello", end="")
print(" World")

Output:

Hello World

Method 2: Using the sep parameter

The print() function also has an optional parameter called sep which allows you to specify the separator between multiple values. By default, the separator is a space, but you can change it to any other character, including an empty string, which will prevent the separator from being added after the output.

print("Hello", "World", sep="")

Output:

HelloWorld

Example: Printing a Progress Bar

A common use case for printing without a new line is to create a progress bar. The following example demonstrates how to create a simple progress bar that displays the percentage of completion.

import time

# Progress bar function
def progress_bar(percentage):
    bar_length = 50
    blocks = int(bar_length * percentage / 100)
    text = "\rPercentage: [{0}] {1}%".format("#" * blocks + "-" * (bar_length - blocks), percentage)
    print(text, end="")

# Main loop
for i in range(101):
    progress_bar(i)
    time.sleep(0.1)

Output:

Percentage: [##################################################] 100%

In conclusion, the end and sep parameters of the print() function allow you to control the output of the function, including printing without a new line. Whether you want to print multiple values on the same line or create a progress bar, these parameters can help you achieve your desired output.

Leave a Reply

Your email address will not be published. Required fields are marked *