How can I print multiple things on the same line, one at a time? Ask Question

How can I print multiple things on the same line, one at a time? Ask Question

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installing XXX... first and then I print [DONE].

How can I instead print Installing xxx... and [DONE] on the same line?


For the specific problem of writing a new message on the same line, replacing what was there before, please see How to overwrite the previous print to stdout?. Most answers here interpreted the question as being about writing new text at the end of the current line.

For the problem of using a single print to output multiple things at once, see How can I print multiple things (fixed text and/or variable values) on the same line, all at once?.

ベストアンサー1

Python 3 Solution

The print() function accepts an end parameter which defaults to \n (new line). Setting it to an empty string prevents it from issuing a new line at the end of the line.

def install_xxx():
    print("Installing XXX...      ", end="", flush=True)

install_xxx()
print("[DONE]")

Python 2 Solution

Putting a comma on the end of the print() line prevents print() from issuing a new line (you should note that there will be an extra space at the end of the output).

def install_xxx():
   print "Installing XXX...      ",

install_xxx()
print "[DONE]"

おすすめ記事