Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Search

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

Written byJeremy Grifski inCode Published September 13, 2019Last Updated May 24, 2020
How to Print on the Same Line in Python Featured Image

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.

Table of Contents

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:

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

As you can probably imagine, the defaultprint function in Java is going to print without a newline character. In contrast, theprintln function is going to behave much like theprint 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 theprint function in Python automatically prints a newline character with each call, then there’s no way to get the Javaprint 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 allversions 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:

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:

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 tosys.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 thesys library:write. This functions works just like theprint function, but there’s no implicit newline:

import syssys.stdout.write("Breaking Bad")

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

import syssys.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 calledend which defaults to some newline character. You can easily change it as follows:

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:

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 thetimeit library for a quick and dirty performance test:

>>> 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, theprint function has quite a bit of overhead. In other words, if performance matters, go thewrite 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:

# Python 2 onlyprint "Live PD",# Backwards compatible (also fastest)import syssys.stdout.write("Breaking Bad")# Python 3 onlyprint("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 bybecoming a member of the communityOpens in a new tab. orhopping 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!

How to Python (42 Articles)—Series Navigation

The How to Python tutorial series strays from the usual in-depth coding articles by exploring byte-sized problems in Python. In this series, students will dive into unique topics such asHow to Invert a Dictionary,How to Sum Elements of Two Lists, andHow to Check if a File Exists.

Each problem is explored from the naive approach to the ideal solution. Occasionally, there’ll be some just-for-fun solutions too. At the end of every article, you’ll find a recap full of code snippets for your own use. Don’t be afraid to take what you need!

If you’re not sure where to start, I recommend checking out our list ofPython Code Snippets for Everyday Problems. In addition, you can find some of the snippets in aJupyter notebook format on GitHubOpens in a new tab.,

If you have a problem of your own, feel free to ask. Someone else probably has the same problem. Enjoy How to Python!

Jeremy Grifski

Jeremy grew up in a small town where he enjoyed playing soccer and video games, practicing taekwondo, and trading Pokémon cards. Once out of the nest, he pursued a Bachelors in Computer Engineering with a minor in Game Design. After college, he spent about two years writing software for a major engineering company. Then, he earned a master's in Computer Science and Engineering. Most recently, he earned a PhD in Engineering Education and now works as a Lecturer. In his spare time, Jeremy enjoys spending time with his wife and kid, playing Overwatch 2, Lethal Company, and Baldur's Gate 3, reading manga, watching Penguins hockey, and traveling the world.

Recent Posts

link to Life Update: I'm Doing Well

Life Update: I'm Doing Well

I wanted to take a moment to just talk about how I'm doing, which is really well actually.

link to The Worst Use Cases for Generative AI That Are Already Mainstream

The Worst Use Cases for Generative AI That Are Already Mainstream

This article looks at several use cases of generative AI that I find dystopian at best, and I want to talk about them.

About Me

Welcome to The Renegade Coder, a coding curriculum website run by myself,Jeremy Grifski. If you like what you see, considersubscribing to my newsletter. Right now,new subscribers will receive a copy of my Python 3 Beginner Cheat Sheet. If newsletters aren't your thing, there are at least 4 other waysyou can help grow The Renegade Coder. I appreciate the support!

Legal

The Renegade Coder is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com.






Longest Active Series


[8]ページ先頭

©2009-2025 Movatter.jp