How to print without a newline or space

Learn how to print without a newline or space with practical examples, diagrams, and best practices. Covers python, trailing-newline development techniques with visual explanations.

Mastering Python's Print: No Newline, No Space

Hero image for How to print without a newline or space

Learn how to control Python's print() function to suppress newlines and spaces, enabling precise output formatting for various use cases.

The print() function in Python is incredibly versatile, but its default behavior of adding a newline character and separating arguments with a space isn't always what you need. This article will guide you through the simple yet powerful ways to modify print()'s behavior, allowing you to print output without a trailing newline or an unwanted space between items. This is crucial for tasks like building progress bars, concatenating output on a single line, or generating specific file formats.

Understanding Default print() Behavior

By default, the print() function in Python automatically appends a newline character (\n) at the end of its output. Additionally, when you pass multiple arguments to print(), it separates them with a single space. This behavior is convenient for most console output but can be a hindrance when you need fine-grained control over the printed string.

print("Hello")
print("World")

print("Hello", "World")

Default print() behavior with newlines and spaces

The output of the above code will be:

Hello
World
Hello World

Notice how each print() call starts on a new line, and the two arguments in the third print() call are separated by a space.

Suppressing the Trailing Newline

The print() function accepts an optional keyword argument called end. By default, end is set to \n. To prevent print() from adding a newline, you can set end to an empty string ('') or any other desired string.

print("This will be on the same line", end='')
print(" as this.")

print("Progress: ", end='')
for i in range(5):
    print(f"{i+1}", end=' ')
print("Done!")

Using the end argument to suppress newlines

The output will now look like this:

This will be on the same line as this.
Progress: 1 2 3 4 5 Done!

This technique is particularly useful for creating dynamic output like progress indicators or single-line log messages.

flowchart TD
    A[Start Print Call] --> B{Arguments Provided?}
    B -->|Yes| C[Separate with 'sep' (default space)]
    B -->|No| D[Print Arguments]
    D --> E[Append 'end' (default newline)]
    E --> F[End Print Call]

Flowchart of Python's print() function default behavior

Controlling the Separator Between Arguments

When print() is called with multiple arguments, it uses another optional keyword argument, sep, to determine what string to place between them. By default, sep is a single space (' '). To remove this space, you can set sep to an empty string ('').

print("No", "space", "here", sep='')
print("Date:", 2023, 10, 26, sep='-')
print("Hello", "World", sep='_')

Using the sep argument to control argument separation

The output will be:

Nospacehere
Date:2023-10-26
Hello_World

This is very effective for concatenating strings or numbers without explicit string formatting, especially when you need a specific delimiter or no delimiter at all.

Practical Applications and Best Practices

Understanding end and sep allows for more dynamic and controlled console output. Here are a few common scenarios where these parameters are invaluable:

1. Building a Progress Bar

Use end='\r' (carriage return) to overwrite the current line, creating a dynamic progress bar without cluttering the console with new lines for each update.

2. Concatenating Log Messages

For logging systems, you might want to print multiple pieces of information on a single line without spaces, using sep=''.

3. Generating Formatted Strings

When constructing specific string formats (e.g., file paths, URLs, or custom data formats), sep can precisely control delimiters.

import time

print("Downloading: ", end='')
for i in range(11):
    print(f"[{'#' * i}{'.' * (10 - i)}] {i*10}%\r", end='')
    time.sleep(0.1)
print("\nDownload Complete!")

Example of a simple progress bar using end='\r'