Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

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

  1. Getting Started with Python: Install, Run, and Write Your First Program
  2. Mastering Python I/O and Module Imports: A Practical Guide
  3. Retrieve Current Date and Time in Python: A Practical Guide
  4. Install Python and PyCharm on Windows: Step‑by‑Step Guide
  5. Python Print() Function: A Practical Guide with Examples
  6. Checking File and Directory Existence in Python – A Practical Guide
  7. Mastering Python’s readline() – Efficient Line‑by‑Line File Reading
  8. Calculating Averages in Python: A Practical Guide
  9. Avoiding Common Pitfalls: Proper Exception Handling in Python
  10. Print Directly from USB on Your Ender 3: A Step‑by‑Step Guide