How to print in same line in Python
1. Using the end
Parameter in print()
The print()
function by default ends its output with a newline (\n)
. To print on the same line, you can use the end
parameter to replace the newline with another character, such as a space.
Syntax:
print("text", end="replacement_string")
- Default behavior:
end="\n"
(adds a newline after the printed text). - If you change
end
to another value (like a space), it prevents the newline.
print("Welcome", end=" ")
print("to Jobinge")
Output:
Welcome to Jobinge
Explanation:
- The first
print()
outputs"Welcome"
without adding a newline, asend=" "
replaces it with a space. - The second
print()
outputs"to Jobinge"
immediately after.
2. Using String Concatenation or Formatting
You can concatenate strings or format them to print everything in a single statement on the same line.
Example 1: String Concatenation
print("Welcome" + " " + "to Jobinge")
Output:
Welcome to Jobinge
Explanation:
"Welcome"
, a space (" "
), and"to Jobinge"
are concatenated into a single string and printed.
Example 2: String Formatting with f-strings
platform = "Jobinge"
print(f"Welcome to {platform}")
Output:
Welcome to Jobinge
Explanation:
- Using f-strings (formatted strings), the value of
platform
is dynamically inserted into the string.
3. Printing in a Loop on the Same Line
When printing multiple items in a loop, use the end
parameter to avoid starting a new line for each iteration.
Example:
for word in ["Welcome", "to", "Jobinge"]:
print(word, end=" ")
Output:
Welcome to Jobinge
Explanation:
- Each word is printed on the same line with a space (
end=" "
) instead of a newline after eachprint()
.
4. Flushing the Output in Real-Time
Sometimes, when printing in loops, the output may be buffered (delayed). Use flush=True
to force immediate display of the output.
Example:
import time
for word in ["Welcome", "to", "Jobinge"]:
print(word, end=" ", flush=True)
time.sleep(1)
Output (appears one word at a time):
Welcome to Jobinge
Explanation:
- The
flush=True
forces immediate printing of each word. time.sleep(1)
adds a 1-second delay for demonstration.
5. Using sys.stdout.write
For precise control over output, use sys.stdout.write()
. Unlike print()
, it does not automatically add a newline (\n
).
Example:
import sys
sys.stdout.write("Welcome ")
sys.stdout.write("to Jobinge\n")
Output:
Welcome to Jobinge
Explanation:
sys.stdout.write("Welcome ")
writes"Welcome "
without adding a newline.sys.stdout.write("to Jobinge\n")
appends"to Jobinge"
followed by a newline (\n
).
Summary
The best ways to print in the same line are given below:
- For simple cases, use
print(..., end="...")
. - Use string concatenation or f-strings to combine dynamic content.
- Use
flush=True
for real-time output in loops. - Use
sys.stdout.write
for low-level control.