How To Use End In Python

7 min read

How to Use the end Parameter in Python

The end parameter is a hidden gem in Python’s print() function that lets you control what character appears at the end of each printed line. Think about it: by default, print() adds a newline character (\n), which moves the cursor to the next line. In practice, changing this behavior with end opens up a range of creative possibilities for formatting output, building progress indicators, and even mimicking other languages’ printing styles. Whether you’re a beginner learning Python basics or an experienced developer looking to refine your console output, mastering end can make your scripts more flexible and visually appealing.

What Is the end Parameter?

In Python, every function has parameters that define its behavior. The print() function is no exception. Its signature looks like this:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
  • *objects: The items you want to print.
  • sep=' ': The separator placed between objects.
  • end='\n': The string appended after the last object. This is the focus of our discussion.
  • file=sys.stdout: Where the output is sent (usually the console).
  • flush=False: Whether to flush the output buffer immediately.

The end parameter defaults to a newline ('\n'). By specifying a different value, you can suppress the newline, replace it with a space, or even embed special characters like ANSI codes for colored output The details matter here..

Basic Usage of end

Changing the line terminator is straightforward. Here’s a simple example that prints two words on the same line:

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

Output:
Hello World

Notice how the space after Hello is supplied by the end=" " argument. The second print() then adds its own newline, resulting in a single line of text Worth keeping that in mind..

Example 1: Printing a Sequence Without Newlines

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

Output:
0 1 2 3 4

The loop prints each number followed by a space, keeping everything on one line. This technique is handy when you need to generate a list of items in a compact format Easy to understand, harder to ignore. Turns out it matters..

Changing Line Separators

The end parameter isn’t limited to spaces. You can use any string, including custom separators, punctuation, or even empty strings.

Example 2: Using a Comma as a Separator

print("Apple", end=", ")
print("Banana", end=", ")
print("Cherry")

Output:
Apple, Banana, Cherry

Here, each print() call adds a comma and a space, and the final call uses the default newline to finish the line.

Example 3: No Separator at All

print("Python", end="")
print("Rocks")

Output:
PythonRocks

Both strings are concatenated directly, which can be useful when building larger strings incrementally.

Combining end with Other print() Parameters

The end parameter works naturally with sep and file. Understanding how they interact helps you craft more sophisticated output.

Using sep and end Together

print("Alice", "Bob", "Charlie", sep=" | ", end=" !!!\n")

Output:
Alice | Bob | Charlie !!!

In this case, sep controls the delimiter between names, while end adds a custom suffix before the newline.

Directing Output to a File

You can also redirect output to a file while customizing the line ending:

with open("output.txt", "w") as f:
    print("First line", end="\n", file=f)
    print("Second line", end="", file=f)
    print("Third line", file=f)

The resulting output.txt will contain:

First line
Second lineThird line

Notice how the second line’s end="" prevents a newline, causing the third line to appear on the same line Not complicated — just consistent..

Practical Examples: Real‑World Uses of end

1. Building Progress Bars

A common pattern in command‑line tools is to display a progress bar that updates in place. Using end='\r' ( carriage return) allows you to overwrite the same line:

import time
import sys

for i in range(1, 11):
    percent = i / 10 * 100
    sys.stdout.Think about it: write(f"\rProgress: {percent:. Plus, 0f}%")
    sys. Worth adding: stdout. Because of that, flush()
    time. Practically speaking, sleep(0. 5)
print("\nDone!

`sys.stdout.write` is used here because it doesn’t automatically add a newline. This leads to the `end='\r'` (via `print(... , end='\r')`) would also work, but `write` gives more control.

#### 2. Logging Without Newlines

Once you want to log multiple pieces of information on a single line, `end=''` can keep the line open:

```python
import datetime

timestamp = datetime.strftime("%H:%M:%S")
print(f"[{timestamp}]", end=" ")
print("User logged in", end=" ")
print("from 192.datetime.On top of that, 168. now().1.

**Output:**  
`[14:35:22] User logged in from 192.168.1.1`

All three `print()` calls share the same line, creating a compact log entry.

#### 3. Mimicking Other Languages

In languages like C, `printf` does not automatically add a newline. Python’s `end` lets you emulate that behavior:

```c
// C equivalent
printf("Hello");
printf(" World");

Python version:

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

Output:
Hello World

Advanced Techniques

Customizing with ANSI Escape Codes

You can combine end with ANSI codes for colored or styled output:

RED = "\033[91m"
BOLD = "\033[1m"
RESET = "\033[0m"

print(BOLD + "Warning:" + RESET, end=" ")
print(RED + "This is dangerous!" + RESET)

Output: (bold warning in default color, then red text)

The end=" " ensures the warning and the dangerous message appear on the same line.

Using end with io.StringIO

When you need to capture printed output in memory, end still applies:

from io import StringIO

buffer = StringIO()
print("Line one", end=" | ", file=buffer)
print("Line two", file=buffer)

print(buffer.getvalue())

Result:

Line one | Line two

Redirect

Redirecting the standard output stream while still controlling the end argument lets you build sophisticated logging pipelines or capture incremental progress without littering your code with manual newline handling. Take this case: you can temporarily replace sys.stdout with a custom file‑like object that buffers chunks and flushes them only when a delimiter appears:

import sys
from io import StringIO

class ChunkCollector:
    def __init__(self):
        self.buffer = StringIO()
        self.pending = ""

    def write(self, data):
        # Accumulate until we see a newline that we deliberately suppressed
        self.pending += data
        if self.Think about it: pending. Worth adding: endswith("\n"):   # only flush when a real newline occurs
            self. Now, buffer. On top of that, write(self. pending)
            self.

    def flush(self):
        if self.Worth adding: pending:
            self. So buffer. write(self.Now, pending)
            self. This leads to pending = ""
        self. buffer.

    def getvalue(self):
        self.flush()
        return self.buffer.getvalue()

# Usage
collector = ChunkCollector()
original_stdout = sys.stdout
sys.stdout = collector

print("Step 1", end="")          # no newline → stays in pending
print(" – in progress", end="") # still pending
print()                          # explicit newline triggers flush
print("Step 2 complete")        # normal line, also flushed

sys.stdout = original_stdout
print("Captured output:")
print(collector.getvalue())

The collector treats any print(..., end="") as part of an ongoing chunk; only when a genuine newline is emitted does it commit the text to the underlying buffer. This pattern is handy for:

  • Live dashboards where you want to overwrite a line (end='\r') but still retain a full log for later analysis.
  • Testing frameworks that need to assert on partial output without interfering with the test runner’s own formatting.
  • Interactive notebooks where you wish to stream intermediate results to a cell while preserving a complete record for export.

Combining end with Context Managers

Python’s contextlib.redirect_stdout (or redirect_stderr) works naturally with custom end values:

from contextlib import redirect_stdout
with open("log.txt", "w") as f, redirect_stdout(f):
    print("Starting", end=" ")
    print("process", end="")
    print()                     # forces a newline in the file
    print("Intermediate step", end="\r")
    print("Done")               # overwrites the previous line in the file

The resulting log.txt contains:

Starting process
Done

Notice how the \r caused the second line to overwrite the first, yet the file still reflects the final state after the overwrite—exactly what you’d see in a terminal.

Practical Tips

  1. Prefer sys.stdout.write for low‑level control when you need to avoid the overhead of print’s argument parsing, but remember to manually handle end if you want to suppress or customize the terminator.
  2. Flush deliberately (sys.stdout.flush() or print(..., flush=True)) when using end='\r' or end='' in long‑running loops; otherwise output may stay buffered and appear delayed.
  3. Combine with libraries like tqdm or rich that already manage line overwriting; you can still pass a custom end to their write methods for niche cases.
  4. Avoid mixing buffered and unbuffered streams in the same thread without explicit flushing, as it can lead to interleaved output that’s hard to debug.

Conclusion

The end parameter of Python’s print function is far more than a simple newline toggle—it’s a versatile tool for shaping how text appears in terminals, files, and in‑memory buffers. That said, by mastering its interaction with redirection, context managers, and manual flushing, you can craft everything from minimalist progress bars to sophisticated logging systems that capture both real‑time feedback and a permanent audit trail. Whether you’re emulating C‑style printf, building live dashboards, or redirecting output for testing, a thoughtful use of end gives you precise command over the flow of information without sacrificing readability or reliability. Embrace it, and your command‑line and file‑based output will become as flexible as the rest of your Python code.

Out the Door

Just Made It Online

Related Corners

On a Similar Note

Thank you for reading about How To Use End In Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home