Lernpfad
The print()
function in Python is commonly used to display output in the console. By default, Python’s print()
function adds a newline character at the end of its output, causing the next output to start on a new line.
While this behavior is convenient in some scenarios, it is important to understand cases where you want to print the output without adding a new line. In this tutorial, we will look at how to use the end
parameter, the sys
module, and string concatenation to print without adding a new line.
Before we get started, I recommend taking DataCamp’s Introduction to Python course to learn the basics of Python for data science and analysis. Also, check out our A Comprehensive Guide on How to Line Break in Python tutorial to learn about the opposite behavior, which is using \n
to add line breaks in strings and print()
statements.
How to Print Without a New Line in Python
To print without adding a new line in Python, you can use the end
parameter in the print()
function. If you set the end
parameter to an empty string, the output continues in the same line.
# Print without newline
print("Hello", end=" ")
print("World", end=" ")
Hello World
Notice that we use two print()
functions here. This might seem unusual to beginners, but it's an important technique. Each print()
call can still control its own output using the end
parameter. In this example, setting end=” “
adds a space after each string instead of a new line, allowing the second print()
statement to continue on the same line.
This approach is particularly useful when you need to print multiple pieces of text or variables over time, but you want them all to appear on the same line with specific formatting (such as spaces or punctuation in between).
Why Print Without a New Line in Python?
In Python, printing without a new line refers to controlling the output such that it does not append the newline character \n
after every print()
callout. Understanding how to override this behavior is important for creating controlled outputs. The following are some of the examples where continuous output may be required.
- Progress Indicators: Progress updates or progress bars require continuous outputs for real-time monitoring.
- Logging: Logging and monitoring also require printing in continuous lines for improved readability.
- Interactive Console Applications: Displaying some user outputs in the same line improves user experiences.
If you’re interested in shifting focus from controlling output in the console to understanding how to add, manage, and remove newline characters in text and files, head over to our Python New Line: Methods for Code Formatting tutorial for techniques and examples.
Become an ML Scientist
Print Without New Line: Python 2 vs. Python 3
To ensure you print the output without adding a new line, you can use the end
parameter or other methods to override the default behavior of the print()
function.
Using the end parameter in Python 3
In Python version 3, you should include the end
parameter in each print()
function call to print without adding a new line. If you set the end
parameter to an empty string, the output continues on the same line, as shown in the example below.
You can also set the end
parameter to a different character or string. The example below demonstrates how to modify the end
parameter in multiple print()
calls to control how the output is formatted.
# Print without newline
print("Hello ", end="World!")
print(" Learn DataCamp Python tutorial.")
Hello World! Learn DataCamp Python tutorial.
The following example illustrates using the end
parameter with an empty string to print a progress update without a new line. In this example, \r
returns the cursor to the beginning of the line, allowing the output to update in place.
# Import the time module, which provides time-related functions like sleep()
import time
# Loop over a range of numbers from 1 to 5 (inclusive)
for i in range(1, 6):
# Print a loading message with a percentage that updates on the same line
print(f"\rLoading... {i*20}%", end="")
# Pause the execution for 1 second to simulate a loading delay
time.sleep(1)
print("\nDone!")
Loading... 20%
Loading... 40%
Loading... 60%
Loading... 80%
Loading... 100%
Done!
When you run the above code in a Python environment, you will note that the loading percentage will update every second on the same line, creating a simple progress indicator. Check out our Writing Functions in Python if you need some help with writing functions, like the one in the example above.
Exploring new line behavior in Python 2
In Python 2, the print statement is different and adds a new line by default. You can add a comma at the end of the print statement to print without a new line.
# Print without newline
print "Hello",
print "World"
Hello World
The downside of this method is that extra space is added between the printed items, unlike in Python 3, where you can control the characters to be appended in the output.
Other Python Techniques for Printing Without New Line
Python offers some advanced methods for printing without a new line. These methods are mainly used to control the output for complex printing.
Combining the end and sep parameters
The end
and sep
parameters can be used together for more complex formatting. In such scenarios, the sep
parameter usually controls how multiple items are separated when passed to the print()
function. The example below separates the different strings by a comma using the sep
parameter.
# Print without newline
print("Hello", "World", sep=", ", end="!")
Hello, World!
Combining the end
and sep
parameters is beneficial in scenarios such as formatting tabular data or creating progress indicators for improved user experience by improving data presentation.
Using the sys module
The sys.stdout.write()
function from the sys
module offers a method to print without automatically appending a new line. This printing method is usually important where precise output control is needed, such as designing progress indicators and displaying real-time logging.
The example below shows how to print without a new line using the sys
module. Note that we have used the sys.stdout.flush()
function to manually flush the output buffer to ensure the text is displayed immediately. This approach is important for displaying loops and real-time applications.
# Import the sys module
import sys
# Print without new line
sys.stdout.write("Hello, ")
sys.stdout.write("World!")
sys.stdout.flush()
Hello, World!
String concatenation as an alternative approach
String concatenation can also be used to join multiple outputs before printing, avoiding the need for multiple print()
statements and ensuring that no new line is added between outputs. The example below shows this method of string concatenation to print output in a single statement.
# Print without new line using string concatenation
output = "Hello" + " " + "World." + " Learn Python."
print(output)
Hello World. Learn Python.
Conclusion
Printing without a new line is useful for displaying output in a single continuous line. Depending on your Python version, Python offers different printing methods without adding a new line.
If you are looking to improve your Python skills, I recommend taking DataCamp’s Python Toolbox course, which teaches iterators and loops, which was hinted at in this article. Our Python Developer and Data Analyst with Python career tracks will help you stay current as you build practical, job-related skills as a data scientist or analyst.
Become a ML Scientist
Frequently Asked Python Questions
How can I print without a new line in Python?
You can include the end
parameter with an empty string in the print()
function to print without adding a new line.
What is the default behavior of the print() function?
By default, the print()
function adds a new line after every output.
Is Python print without a new line method supported in Python 2 and 3?
In Python 3, you can use the end
parameter in the print()
function to print without a new line. In Python 2, you must add a comma after the print statement to print without a new line.
Why do I get an extra space in the output after using the comma separator in Python 2?
In Python 2, an extra space is added by default between printed items after using the comma to print without a new line. I recommend using other alternative methods to control the characters appended in the output.
Does printing without a newline affect performance?
Printing without a new line has minimal impact on performance. You can use the sys.stdout.write()
from the sys
module for improved performance when handling large data.