Python Print Without Newline: Mastering the end Parameter & Other Techniques
The built‑in print() function is the primary way to display output in Python. By default, it appends a newline (\n) after each call, causing subsequent prints to appear on a new line.
How the Default print() Works
print("Hello World")
print("Welcome to Guru99 Tutorials")
Output:
Hello World Welcome to Guru99 Tutorials
Each string appears on its own line because print() automatically adds the newline character.
Suppressing the Newline in Python 3+
Python 3 introduced the end keyword argument to print(). Setting end="" removes the default newline, allowing you to continue printing on the same line.
print("Hello World ", end="")
print("Welcome to Guru99 Tutorials")
Output:
Hello World Welcome to Guru99 Tutorials
To insert a separator (space, comma, custom string), provide it as the value of end:
print("Hello World ", end=" ")
print("Welcome to Guru99 Tutorials")
Output:
Hello World Welcome to Guru99 Tutorials
print("Hello World ", end="It's a nice day! ")
print("Welcome to Guru99 Tutorials")
Output:
Hello World It's a nice day! Welcome to Guru99 Tutorials
Python 2.x – The Comma Trick
In Python 2, appending a comma after the string prevents the newline:
print "Hello World ", print "Welcome to Guru99 Tutorials."
Output:
Hello World Welcome to Guru99 Tutorials
Using the sys Module
The sys module offers stdout.write() for fine‑grained control over output without automatically adding a newline.
import sys
sys.stdout.write("Hello World ")
sys.stdout.write("Welcome to Guru99 Tutorials")
Output:
Hello World Welcome to Guru99 Tutorials
Printing a List on One Line
When iterating over a list, end=" " keeps all items on the same line:
mylist = ["PHP", "JAVA", "C++", "C", "PYTHON"]
for i in mylist:
print(i, end=" ")
Output:
PHP JAVA C++ C PYTHON
Printing a Continuous Pattern of Stars
Use end="" in a loop to generate a single line of characters:
for i in range(20):
print('*', end="")
Output:
********************
Key Takeaways
- Python’s
print()adds a newline by default. - Use
end=""(Python 3+) or a trailing comma (Python 2) to suppress the newline. - The
sys.stdout.write()method offers an alternative when you need complete control. - When printing collections,
end=" "keeps elements inline.
Python
- Getting Started with Python: Install, Run, and Write Your First Program
- Mastering Python I/O and Module Imports: A Practical Guide
- Retrieve Current Date and Time in Python: A Practical Guide
- Install Python and PyCharm on Windows: Step‑by‑Step Guide
- Python Print() Function: A Practical Guide with Examples
- Checking File and Directory Existence in Python – A Practical Guide
- Mastering Python’s readline() – Efficient Line‑by‑Line File Reading
- Calculating Averages in Python: A Practical Guide
- Avoiding Common Pitfalls: Proper Exception Handling in Python
- Print Directly from USB on Your Ender 3: A Step‑by‑Step Guide