
πDetailed Guide: How to Print Without Newline in Python
How to Print Without Newline in Python: The Python print() function automatically adds a newline at the end by default. However, there are effective ways to print content without a newline in Python. This guide covers multiple methods with examples to help you master this skill.
π1. Using print() with end= Parameter (Python 3+)
In Python 3 and above, the end= parameter controls what gets printed at the end of the statement. By default, end=”\n” adds a newline. To prevent that, use end=””.
π How to Print Without Newline in Python Example:
python
print(“Hello World”, end=””)
print(“Welcome to Software Moji Moji Tutorials”)
π How to Print Without Newline in Python Output:
css
Hello WorldWelcome to Software Moji Moji Tutorials
To add a space between the two strings, modify end= as follows:
python
print(“Hello World”, end=” “)
print(“Welcome to Software Moji Moji Tutorials”)
πHow to Print Without Newline in Python Output:
css
Hello World Welcome to Software Moji Moji Tutorials
You can also add custom text or symbols:
python
print(“Hello World”, end=” – “)
print(“Welcome to Software Moji Moji Tutorials”)
πOutput:
css
Hello World – Welcome to Software Moji Moji Tutorials
π2. Using a Comma (,) in Python 2.x
In Python 2.x, adding a comma at the end of the print statement achieves the same effect.
πExample:
python
print “Hello World”,
print “Welcome to Software Moji Moji Tutorials.”
πOutput:
css
Hello World Welcome to Software Moji Moji Tutorials
π3. Using sys Module for Printing Without Newline
The sys module provides another method to achieve this.
πExample:
python
import sys
sys.stdout.write(“Hello World “)
sys.stdout.write(“Welcome to Software Moji Moji Tutorials”)
πOutput:
css
Hello World Welcome to Software Moji Moji Tutorials
π4. Printing List Elements Without Newline
When printing list items in a loop, use end= to ensure they appear on the same line.
πExample:
python
mylist = [“PHP”, “JAVA”, “C++”, “C”, “PYTHON”]
for item in mylist:
print(item, end=” “)
πOutput:
mathematica
PHP JAVA C++ C PYTHON
π5. Printing Patterns Without Newline
To print patterns like stars (*) without a newline or space, apply end=””.
πExample:
python
for i in range(20):
print(‘*’, end=””)
πOutput:
markdown
πSummary
- The print() function automatically adds a newline, but you can control this with end= in Python 3+.
- In Python 2.x, a comma at the end of the print statement achieves the same result.
- The sys module offers an alternative method for printing without newline.
- Using end= helps in printing list items or patterns in a single line efficiently.