Escape Sequence: Carriage Return (\r) in Python

What is the Carriage Return Escape Sequence?

The carriage return escape sequence \r moves the cursor back to the beginning of the current line without advancing to the next line. When printed, it can overwrite the beginning of the line with new content.

Examples of Using \r

Example 1: Simple Overwrite

In this example, the string "Hello World" is printed. But \rPython moves the cursor to the start and prints "Python", replacing "Hello" with it. So you get "Python World".

Tip: Only the characters at the beginning of the line are replaced, not the entire line.

print("Hello World\rPython")
# Output:
# PythonWorld

Example 2: Partial Overwriting

Here, "1234567890" is printed first. Then \r brings the cursor to the start. "ABCDE" replaces the first 5 characters, resulting in "ABCDE67890".

Key Idea: Characters after the overwritten part are left unchanged.

print("1234567890\rABCDE")
# Output:
# ABCDE67890

Example 3: Progress Indicator

"Loading....." is printed one dot at a time using a loop. Then \r moves the cursor back and "Done!" replaces it, giving a clean output.

Real-world Use: This is often used in command-line tools to show progress or status updates without printing new lines every time.

import time
print("Loading", end="")
for i in range(5):
    print(".", end="", flush=True)
    time.sleep(0.5)
print("\rDone!      ")
# Output:
# Done!      .

Example 4: In a String

The string "Hello\rBye" means "Bye" is printed starting from the beginning, replacing "Hel" from "Hello". The remaining "lo" is kept, resulting in "Byeo".

Why this happens: Strings aren't magically erased — only overwritten. So anything longer than the replacement remains.

text = "Hello\rBye"
print(text)
# Output:
# Byelo

Example 5: Carriage Return with Newline

This example combines both \r and \n. First, "First Line" is overwritten by "Second" due to \r. Then \n prints "Third Line" on the next line.

Note: \n moves to a new line, while \r only moves the cursor to the beginning of the same line.

print("First Line\rSecond\r\nThird Line")
# Output:
# SecondLine
# Third Line

Summary

The \r escape sequence returns the cursor to the beginning of the current line, allowing you to overwrite existing text. It's especially useful for updating lines in terminal output, like showing progress dynamically.