Python

How to Print on the Same Line in Python: Print and Write

As someone who teaches a lot of beginner programming content, I occasionally stumble upon questions like “how do you print on the same line in Python?” Luckily, I have an answer to that!

In short, there are two main ways to print on the same line in Python. For Python 2, use the following print syntax: print "Williamson",. For Python 3, use the following print syntax: print("Providence", end=""). Otherwise, check out the remainder of the article for a backwards compatible solution.

Problem Introduction

In many programming languages, printing on the same line is typically the default behavior. For instance, Java has two command line print functions:

1
2
System.out.print();
System.out.println();

As you can probably imagine, the default print function in Java is going to print without a newline character. In contrast, the println function is going to behave much like the print function in Python. Specifically, it’s going to print whatever string you provide to it followed by a newline character (i.e. \n).

Of course, if the print function in Python automatically prints a newline character with each call, then there’s no way to get the Java print behavior, right? Luckily, that’s not true! Otherwise, I wouldn’t have anything to write about out.

Solutions

In order to print on the same line in Python, there are a few solutions. Unfortunately, not all of the solutions work in all versions of Python, so I’ve provided three solutions: one for Python 2, another for Python 3, and a final solution which works for both.

Print on the Same Line The Old Way

When I was searching for solutions to this problem, I found a lot of material on Python 2 which is quickly phasing out (I hope). That said, I felt this solution would be helpful to anyone still rocking it.

At any rate, when you print something in Python 2, the syntax is the same as Python 3, but you leave out the parentheses:

1
print "Live PD"

Of course, in both cases, the default behavior is to print with a newline. As a result, we’ll need to add a clever bit of syntax—a comma:

1
print "Live PD",

Now, the print function should exclude the newline. However, this solution will add an extra space to the end of the string. Also, you may notice that this solution does not print immediately. If that happens, you can make a call to sys.stdout.flush().

Print on the Same Line with the Write Function

Fortunately, we can bridge the gap between Python 2 and 3 using a function out of the sys library: write. This functions works just like the print function, but there’s no implicit newline:

1
2
import sys
sys.stdout.write("Breaking Bad")

Again, since there is no newline, you may need to flush the buffer to see any results:

1
2
3
import sys
sys.stdout.write("Breaking Bad")
sys.stdout.flush()

In either case, this solution will get the job done in both versions of Python.

Print on the Same Line the New Way

In Python 3, print is a standard function. As a result, it has additional opportunities for parameters. In particular, there is a keyword argument called end which defaults to some newline character. You can easily change it as follows:

1
print("Mob Psycho 100", end="")

And, that’s it! Instead of the string ending in a newline, it will end in an empty string. Of course, this solution comes with the same caveat as the other previous two solutions: you may need to flush the buffer.

Performance

As always, I like to take a look at all the solutions from the point of view of performance. To start, I usually store each solution in a string. To avoid excessive printing during the test, I’ve chosen to write empty strings:

01
02
03
04
05
06
07
08
09
10
11
setup="""
import sys
"""
 
write_solution = """
sys.stdout.write("")
"""
 
print_solution = """
print("", end="")
"""

Unfortunately, I was unable to test the Python 2 solution on my system, so feel free to share your results in the comments. At any rate, I like to use the timeit library for a quick and dirty performance test:

1
2
3
4
5
>>> import timeit
>>> min(timeit.repeat(stmt=write_solution, setup=setup, repeat=10))
0.20978069999999605
>>> min(timeit.repeat(stmt=print_solution, setup=setup, repeat=10))
0.5292953999999952

Clearly, the print function has quite a bit of overhead. In other words, if performance matters, go the write route. Otherwise, print works great!

A Little Recap

Well, that’s it for this one. Check out the code block below for a list of all the solutions:

1
2
3
4
5
6
7
8
9
# Python 2 only
print "Live PD",
 
# Backwards compatible (also fastest)
import sys
sys.stdout.write("Breaking Bad")
 
# Python 3 only
print("Mob Psycho 100", end="")

As always, if you know any other ways to print on the same line in Python, let us know in the comments. In the meantime, why not grow your Python knowledge with the following articles:

If you liked this article or any of the ones I listed, consider sticking around long term by becoming a member of the community or hopping on the mailing list.

While you’re here, why not take advantage of some these Python books:

Otherwise, I appreciate the support. Thanks for stopping by!

Published on Web Code Geeks with permission by Jeremy Grifski, partner at our WCG program. See the original article here: How to Print on the Same Line in Python: Print and Write

Opinions expressed by Web Code Geeks contributors are their own.

Jeremy Grifski

Jeremy is the founder of The Renegade Coder, a software curriculum website launched in 2017. In addition, he is a PhD student with an interest in education and data visualization.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button