askvity

How to Print on the Same Line in Python?

Published in Print Formatting 3 mins read

To print on the same line in Python, you need to modify the default behavior of the print() function, which automatically adds a newline character at the end of each output. Here's how to achieve this in different Python versions:

Python 3

In Python 3, the print() function has an end parameter that controls what's added at the end of the output. By default, end is set to \n (newline). To print on the same line, you can set end to an empty string ("") or any other character you prefer (e.g., a space " ").

Example:

print("This will be printed", end=" ")
print("on the same line.")

print("Item 1", end=", ")
print("Item 2", end=", ")
print("Item 3")

This code will produce:

This will be printed on the same line.
Item 1, Item 2, Item 3

Explanation:

  • print("text", end=""): This ensures that no newline is added at the end of the "text" and the subsequent print statement will continue on the same line.
  • print("text", end=" "): Instead of a newline, a space is added.
  • You can use any string value for the end parameter.

Python 2

In Python 2, the print statement is not a function like in Python 3. To print on the same line in Python 2, you should add a comma (,) after the print statement.

Example:

print "This will be printed",
print "on the same line."

print "Item 1",
print "Item 2",
print "Item 3"

This code will produce output similar to this (note the space after the comma is the separator):

This will be printed on the same line.
Item 1 Item 2 Item 3

Explanation:

  • Adding a comma after print "text", suppresses the addition of the newline, causing the next print statement to output on the same line.
  • By default, Python 2 inserts a single space as the separator between comma separated items.

Summary

Python Version Method end Parameter Example
Python 3 print("text", end="...") Available print("Hello", end=" ")
Python 2 print "text", Not available print "Hello",

Conclusion:

Both Python 2 and Python 3 allow you to print on the same line. In Python 3, you use the end parameter, while in Python 2, you use a comma. Knowing these differences is important when working with different Python versions.

Related Articles